码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Flatten Binary Tree to Linked List

时间:2014-12-23 00:05:27      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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
思路:
先序遍历的变形,有两种方法。一种从上往下,一种从下往上。
先说从上往下。从根节点开始,将当前节点的坐节点移到右节点上,原来的右节点与现在的最右节点相连。这样,当前节点的左边就为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 flatten(TreeNode *root) {
        if(root==NULL)
            return;
        if(root->left) {
            TreeNode *tmp = root->right;
            root->right = root->left;
            root->left = NULL;
            TreeNode *LastRight = root;
            while(root->right)
                root = root->right;
            root->right = tmp;
            root = LastRight;
        }
        flatten(root->right);
    }
};
从上往下
技术分享
/**
 * 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;
        if(root->left==NULL && root->right==NULL)
            return;
        flatten(root->right);
        flatten(root->left);
        TreeNode *tmp = root->right;
        if(root->left)
        {
            root->right = root->left;
            root->left  = NULL;
            while(root->right)
                root = root->right;
            root->right = tmp;
        }
    }
};
从下往上

 

 

[leetcode] Flatten Binary Tree to Linked List

标签:

原文地址:http://www.cnblogs.com/jiasaidongqi/p/4179199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!