Wednesday, November 19, 2014

Flatten Binary Tree to LinkedList LeetCode

Recursion

public TreeNode lastNode = null;
    public void flatten(TreeNode root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
       if (root == null) return;
       if (lastNode != null) {
           lastNode.left = null;
           lastNode.right = root;
       }
     
       TreeNode left = root.left;
       TreeNode right = root.right;
       lastNode = root;
       flatten(left);
       flatten(right);
    }

No comments:

Post a Comment