标签:des style blog io ar color sp for java
题目 |
Binary Tree Level Order Traversal II |
通过率 | 30.6% |
难度 | Easy |
Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
问题实质:二叉树的层次遍历(即广度优先)
关键点在于遍历上一层的过程把下一层的节点得到,然后再通过节点的list列表读取到每个节点的值,然后把每一层所有节点的值存入一个list列表,然后再把每一层的list列表作为最终list列表的元素。同样不能忘了空树的情况!
java代码如下:
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 ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { 12 ArrayList<ArrayList<Integer>> resultFinal = new ArrayList<ArrayList<Integer>>(); 13 ArrayList<TreeNode> treeNodeTemp = new ArrayList<TreeNode>(); 14 if(root==null){ 15 return resultFinal; 16 }else 17 { 18 treeNodeTemp.add(root); 19 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 20 while(treeNodeTemp.size()!=0) 21 { 22 ArrayList<Integer> resultTemp = new ArrayList<Integer>(); 23 ArrayList<TreeNode> treeNodeTempWhile = new ArrayList<TreeNode>(); 24 for(int i=0; i<treeNodeTemp.size();i++) 25 { 26 TreeNode node = treeNodeTemp.get(i); 27 resultTemp.add(node.val); 28 if(node.left != null) 29 { 30 treeNodeTempWhile.add(node.left); 31 } 32 if(node.right != null) 33 { 34 treeNodeTempWhile.add(node.right); 35 } 36 } 37 result.add(resultTemp); 38 treeNodeTemp = treeNodeTempWhile; 39 } 40 for(int i=result.size()-1; i>=0;i--) 41 { 42 resultFinal.add(result.get(i)); 43 } 44 } 45 return resultFinal; 46 } 47 }
一套题目前前后后写了一晚上,中间还顺带瞅瞅让人不知是爱是恨的辩证法,不管怎样,最后的代码通过啦,希望明天的考试不管过程多曲折,结果是美好的。
2014-12-13
22:53:13
软微5218
leetcode----------Binary Tree Level Order Traversal II
标签:des style blog io ar color sp for java
原文地址:http://www.cnblogs.com/pku-min/p/4162007.html