Sunday, March 3, 2013

[LeetCode] Flatten Binary Tree to Linked List


Thought:
Recursion, after flatten the left subtree and the right subtree, we should do some small adjustment.

Code:
public class Solution {
    public void flatten(TreeNode root) {
        if (root == null) return;
        else if (root.left == null && root.right == null) return;
        else {
            flatten(root.left);
            flatten(root.right);
            TreeNode flag = root.left;
            if (flag != null) { 
                while (flag.right != null) {
                    flag = flag.right;            
                }
                flag.right = root.right;
                root.right = root.left;
                root.left = null;
            }
        }
    }
}

No comments:

Post a Comment