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;
            }
        }
    };
  • 相关阅读:
    C#继承之构造函数
    .Net Framework: 字符串的驻留(String Interning)
    解码 XML 和 DTD
    Java的静态变量初始化的坑
    创建执行jar包脚本
    jasypt 加密
    测试@Transactional
    linux如何查看端口被哪个进程占用
    径向基函数工作原理(样条函数)
    反距离权重插值的工作原理
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3672002.html
Copyright © 2011-2022 走看看