114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

1

/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:

1
\
2
\
3
\
4
\
5
\
6

Solution

中序遍历,递归flatten Tree
注意:root.left 要置null

Complexity

O(N) O(1****)

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        helper(root);
    }
    
    public void helper(TreeNode root){
        if(root == null)
            return;
        TreeNode right = root.right;
        TreeNode left = root.left;
        
        helper(left);    
        
        root.left = null;
        if(left != null){
            root.right = left;
            TreeNode node = left;
            while(left.right != null)
                left = left.right;
            left.right = right;
        }
        
        helper(right); 
    }
}