leetcode Flatten Binary Tree to Linked List

265 篇文章 1 订阅
231 篇文章 0 订阅

 

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

 

 

I finished this problem in a direct way. However, the result was Runtime Error because I didn't set the left child to null when I submitted the first time.

 

 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private :
  vector<TreeNode *> temp ;// record the preOrder result 
public:
   void preOrder(TreeNode *root){
    temp.push_back(root);
    if(root->left) preOrder(root->left);
    if(root->right) preOrder(root->right);
   
   }
    void flatten(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        temp.clear();
        if(root == NULL) return ;
        preOrder(root);
        for(int i = 0; i< temp.size()-1; i++)
         {
            temp[i]->right = temp[i+1];
            temp[i]->left = NULL ;//essential
         }
       
    }
};

 

 

There is another way to solve this problem. Initially, root-->left, root-->right, 

if(root->left==null)

nothing needs to do.

if(root->left!=null){

find the rightest node of root->left

rightest node->next=root->right;

root->right=root->left; //because of the pre-order

}

The following is the code :

 

/**
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        TreeNode *p;
        if(root==NULL)  return;
        flatten(root->left);
        flatten(root->right);
        if(root->left==NULL)    return;
        p=root->left;
        while(p->right!=NULL)   p=p->right;
        p->right=root->right;
        root->right=root->left;
        root->left=NULL;
        
		return;
    }
};

Python Nonrecursive Version (Preorder, ref to https://blog.csdn.net/taoqick/article/details/82495508):

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def flatten(self, root):
        stack = []
        prev,cur = None,root
        while (cur != None or stack):
            while (cur != None):
                if (cur.right != None):
                    stack.append(cur.right)
                if (prev != None):
                    prev.left = None
                    prev.right = cur
                
                prev = cur
                cur = cur.left
            if (stack):
                cur = stack.pop()

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值