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

[LeetCode] Flatten Binary Tree to Linked List

时间:2015-08-11 18:44:03      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:c++   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

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.

解题思路:

题意为将二叉树按照先序遍历压平。最开始时对in-place理解错误,以为空间复杂度只能为O(1)。其实不然(我们姑且认为递归的时候空间不变)。

我们可以用递归来解决这个问题。

首先定义个递归函数,改递归函数返回root为根节点的最右节点。

倘若root->left不为空,则将左子树的节点插入到root->right中。

递归代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        flattenHelper(root);
    }
    
    //返回root为根的最右边的那个节点
    TreeNode* flattenHelper(TreeNode* root){
        if(root == NULL){
            return NULL;
        }
        TreeNode* leftMost = flattenHelper(root->left);
        TreeNode* rightMost = flattenHelper(root->right);
        if(leftMost!=NULL){
            TreeNode* temp = root->right;
            root->right = root->left;
            root->left = NULL;
            leftMost->right = temp;
        }
        
        if(leftMost==NULL&&rightMost==NULL){
            return root;
        }else if(rightMost==NULL){
            return leftMost;
        }else{
            return rightMost;
        }
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Flatten Binary Tree to Linked List

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47424333

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