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;
            }
        }
    };
  • 相关阅读:
    WSGIRequest对象 和querydict对象
    限制请求method及页面重定向
    ORM模型里连接数据库常用方法和QuerySet API
    orm模型(关于时区时间)
    spring mvc 前后端数据交互方式(整理)
    java 国际化(转载)
    spring 基础学习笔记
    (转载)java nio 原理解析
    collection 所有集合的接口。
    java.lang.String类
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3672002.html
Copyright © 2011-2022 走看看