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

Leetcode: Flatten Binary Tree to Linked List

时间:2014-09-16 04:57:10      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   sp   log   

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.

难度:70

把先序遍历的结果存到一个ArrayList<TreeNode>里面,然后从根节点开始,依次把左子树置空,右子树置为ArrayList里面存的下一个节点

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public void flatten(TreeNode root) {
12         if (root == null) return;
13         ArrayList<TreeNode> preorder = new ArrayList<TreeNode>();
14         helper(root, preorder);
15         preorder.remove(0);
16         TreeNode temp = root;
17         while (preorder.size()!=0) {
18             temp.left = null;
19             temp.right = preorder.get(0);
20             preorder.remove(0);
21             temp = temp.right;
22         }
23     }
24     
25     public void helper(TreeNode root, ArrayList<TreeNode> preorder) {
26         if (root == null) return;
27         preorder.add(root);
28         helper(root.left, preorder);
29         helper(root.right, preorder);
30     }
31 }

需要注意看一个arraylist是否为减为空应该是看它的size是否等于0,而不是arraylist == null,后者表示没有给该arraylist分配地址

Leetcode: Flatten Binary Tree to Linked List

标签:style   blog   color   io   ar   for   div   sp   log   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3974099.html

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