Flatten Binary Tree to Linked List, Leetcode 解题笔记

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
click to show hints.

Hints:
If you notice carefully in the flattened tree, each node’s right child points to the next node of a pre-order traversal.

这个递归太巧妙了,自己没有想到,像这种要改变node的孩子的情况,要考虑运用lastVisitedNode。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode lastVisited = null;
    public void flatten(TreeNode root) {
        if(root == null) return;
        TreeNode right = root.right;
        if(lastVisited != null){
            lastVisited.right = root;
            lastVisited.left = null;
        }
        lastVisited = root;
        flatten(root.left);
        flatten(right);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s