114. 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

 

class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        def dfs(root):
            if root == None:
                return 
            
            left = self.flatten(root.left)
            right = self.flatten(root.right)
            
            root.left = None
            root.right = left
            cur = root
            while cur.right != None:
                cur = cur.right
            cur.right = right
            return root
        return dfs(root)

 

 

 

 

class Solution {
public:
    void flatten(TreeNode* root) {
      if (root == nullptr) return;
      flatten(root->left);
      flatten(root->right);

      TreeNode* cur = root->left;
      if(cur == nullptr) return;
      while(cur->right != nullptr) cur=cur->right;
      cur->right = root->right;
      root->right = root->left; 
      root->left = nullptr;
    }
};

 

 

遍历的时候根右左

逆向的前序遍历

 1 class Solution {
 2     public void flatten(TreeNode root) {
 3         root =help(root,null);;
 4         
 5     }
 6     private TreeNode help(TreeNode root,TreeNode prev){
 7         if(root==null) return prev;
 8         //记录下上次访问的节点,
 9         //上次访问的节点就是当前节点的右子树,左子树是null
10         prev = help(root.right,prev);
11         prev = help(root.left,prev);
12         root.right = prev;
13         root.left = null;
14         
15         return root;
16         
17     }
18 }

 

posted @ 2018-01-30 23:27  乐乐章  阅读(145)  评论(0编辑  收藏  举报