码迷,mamicode.com
首页 > 其他好文 > 详细

Flatten Binary Tree to Linked List

时间:2015-03-30 10:52:04      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Flatten Binary Tree to Linked List

标签:

原文地址:http://www.cnblogs.com/ivanyangzhi/p/4377120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!