Flatten Binary Tree to Linked List

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

前序遍历,每层都记录当前节点的左右孩子节点,用tail记录修改后的链表结尾,并返回给上一层。在修改结构之前注意把当前节点的左右置空。

 1 public class FlattenBinaryTreeToLinkedList {
 2     public void flatten(TreeNode root) {
 3         dfs(root);
 4     }
 5 
 6     public TreeNode dfs(TreeNode root) {
 7         if (root == null) {
 8             return null;
 9         }
10         TreeNode left = root.left;
11         TreeNode right = root.right;
12         //将当前节点的左右孩子置空
13         root.left = null;
14         root.right = null;
15         TreeNode tail = root;
16         //连接左子树
17         if (left != null) {
18             tail.right = left;
19             tail = dfs(left);
20         }
21         //连接右子树
22         if (right != null) {
23             tail.right = right;
24             tail = dfs(right);
25         }
26         return tail;
27     }
28 }

 

posted on 2015-03-30 09:06  绿树荫  阅读(154)  评论(0编辑  收藏  举报

导航