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);
    }
    };
  • 相关阅读:
    VijosP1274:神秘的咒语
    2009年浙大 :找出直系亲属
    django用户信息扩展
    缓存
    自定义认证
    自定义admin
    权限的配置和使用
    form表单
    过滤器 自定义查询
    中间件
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3687473.html
Copyright © 2011-2022 走看看