http://www.lintcode.com/en/problem/flatten-binary-tree-to-linked-list/ https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/

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

解题:这道题要求把二叉树转化成类似linked list的形式,每个node right pointer指向下一个node。从例子中不难看出在遍历的时候要把左子树移到右子树的位置上。这题关键是要用一个遍历保存parentnode,当遍历到下一层的时候我们把左子树清空,把左子树append到parentnode右节点上。过程如下图所示,当执行到2的时候,将右子树保存在变量realright中,然后把左子树移到右子树的位置。

   ->1                1(lastvisited)      realright   5
    / \            /      \                            \
   2   5    => ->null      2                            6
  / \   \                 / \
 3   4   6               3   4
 public class Solution {
    TreeNode lastvisited = null;
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }

        TreeNode realright = root.right;
        if (lastvisited != null) {
            lastvisited.left = null;
            lastvisited.right = root;
        }

        //lastvisited keep updating the previous visited node in preoder traverse
        lastvisited = root;
        flatten(root.left);
        flatten(realright);
    }
}

results matching ""

    No results matching ""