zoukankan      html  css  js  c++  java
  • [LeetCode]Flatten Binary Tree to Linked List

    Given a binary tree, flatten it to a linked list in-place.

    For example,
    Given

             1
            / 
           2   5
          /    
         3   4   6
    

    The flattened tree should look like:

       1
        
         2
          
           3
            
             4
              
               5
                
                 6
    Hints:

    If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

    Solution:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* flat(TreeNode *root)
    {
      if(root -> left == NULL)
      {
        if(root -> right == NULL)
        {
          return root;
        }
        else
        {
          return flat(root -> right);
        }
      }
      else
      {
        if(root -> right == NULL)
        {
          root -> right = root -> left;
          root -> left = NULL;
          return flat(root -> right);
        }
        else
        {
          TreeNode *leftEnd = flat(root -> left);
          TreeNode *rightEnd = flat(root -> right);
          TreeNode *tmp = root -> right;
          root -> right = root -> left;
          root -> left = NULL;
          leftEnd -> right = tmp;
          return rightEnd;
        }
      }
        
    }
    
    void flatten(TreeNode *root) {
       if(root == NULL) return;
       flat(root);
    }
    };
  • 相关阅读:
    设计模式-抽象工厂模式
    装修预算-资料收集
    SQL中存储过程和函数的区别
    View
    数据表优化
    Entity Framework 基础
    html5标准
    JS整数验证
    vue 页面切换从右侧切入效果
    vue动态设置Iview的多个Input组件自动获取焦点
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3687473.html
Copyright © 2011-2022 走看看