Flatten a binary tree to a fake "linked list" in pre-order traversal.

Here we use the _right _pointer in TreeNode as the _next _pointer in ListNode.

Example
              1
               \
     1          2
    / \          \
   2   5    =>    3
  / \   \          \
 3   4   6          4
                     \
                      5
                       \
                        6
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    TreeNode prev = null;
    public void flatten(TreeNode root) {
        // write your code here
        if (root == null) {
            return;
        }
        flatten(root.right);
        flatten(root.left);
        root.right = prev;
        root.left =  null;
        prev = root;

    }
}

results matching ""

    No results matching ""