Monday, November 2, 2015

[leetcode] Flatten Binary Tree to Linked List

Again, the recursion principle, pretending the recursive call is a completed API from outside.
这样问题就归类成 左边flatten好的 和右边fallten好的tree 怎么结合了。。自然就出答案了
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public void flatten(TreeNode root) {
        flattening(root);
        return;
    }
    
    private TreeNode flattening(TreeNode root){
        if (root == null) return null;
        TreeNode leftTail = flattening(root.left);
        TreeNode rightTail = flattening(root.right);
        if (root.left != null){
            TreeNode temp = root.right;
            root.right = root.left;
            root.left = null;
            leftTail.right = temp;
        }
        if (rightTail != null){
            return rightTail;
        }
        if (leftTail != null){
            return leftTail;
        }
        return root;
    }
}

No comments:

Post a Comment