zoukankan      html  css  js  c++  java
  • 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
    

    click to show hints.

    Hints:

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

    思路:给定一个二叉树,将它变成一个类似上面那样的链表,而且操作要原地进行.递归处理之后,把右子树连接到处理后的左子树上,然后在把左子树改成右子树,然后再把左子树设为NULL;

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void flattree(TreeNode *root)
        {
            if(root==NULL)
                return;
            flattree(root->left);
            flattree(root->right);
            TreeNode *cur=root;
            if(cur->left==NULL)
                return;
            else
                cur=cur->left;
            while(cur->right!=NULL)
                cur=cur->right;
            cur->right=root->right;
            root->right=root->left;
            root->left=NULL;
        }
        void flatten(TreeNode *root) {
            flattree(root);
        }
    };

    循环方法:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode *root) {
            if(root==NULL)
                return ;
            TreeNode *pPre;
            while(root)
            {
                if(root->left) {
                    pPre=root->left;
                    while(pPre->right)
                        pPre=pPre->right;
                    pPre->right=root->right;
                    root->right=root->left;
                    root->left=NULL;
                }
                root=root->right;
            }
        }
    };
  • 相关阅读:
    Django知识总结(一)
    Django知识总结(二)
    Django知识总结(三)
    机器学习领域主要术语的英文表达
    Python的进程与线程--思维导图
    MySQL数据库--思维导图
    5.18 每日小三练
    5.14 每日小三练
    5.12 每日小三练
    5.9 每日小三练
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3672002.html
Copyright © 2011-2022 走看看