leetcode #114 in cpp

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


Solution:

give the root of a tree, we are going to flatten this tree. The result should only contains right subtree. 

The example in the question shows that the order in the final result should following the pre-order traversal. That is, we traverse the root, then traverse the left subtree, and then we traverse the right subtree. If we are going to make a single linked list, then we have to make sure that right subtree always comes after left subtree. 

Thus we need to:

1. make right subtree left subtree's rightmost node's right child. (ensure right subtree always comes after left subtree)

2. make the new left subtree as the right subtree. And make left subtree as empty.(ensure the final result only contains right subtree)

3. we continue to flatten(new right subtree).


Code:

/**
 * 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) {
        makeFlatten(root);
    }
    void makeFlatten(TreeNode *&root){
        if(!root) return;
        if(!root->right) {//if root right is empty, move root left to root right and delete root left
            root->right = root->left; 
            root->left = NULL;
            makeFlatten(root->right);//continue to flatten next node
            return; 
        }
        if(!root->left){//if root left is empty, we continue to faltten root right
            makeFlatten(root->right);
            return; 
        }
        //store root right as r. move root left to root right, then make r as the right child the right most point in the new right subtree.
        TreeNode *r = root->right; 
        //find the rightmost point in the left subtree
        TreeNode *cur = root->left;
        while(cur->right){
            cur = cur->right;
        }//put leftsubtree as right subtree
        root->right = root->left; 
        //delete left subtree
        root->left = NULL;
        //make r as right child of rightmost point in the new right subtree
        cur->right = r; 
        //continue to flatten right subtree.
        makeFlatten(root->right);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值