public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if (root == null)
return list;
List<TreeNode> mainList = new ArrayList<TreeNode>();
List<Integer> tmpList = new ArrayList<Integer>();
int curr = 0;
Stack<List<Integer>> stack = new Stack<List<Integer>>();
mainList.add(root);
tmpList.add(root.val);
while (mainList.size() > curr) {
int tmp = mainList.size();
List<Integer> newTmpList = new ArrayList<Integer>();
for (int i = curr; i < tmp; i++)
newTmpList.add(tmpList.get(i));
stack.push(newTmpList);
while (tmp > curr) {
TreeNode node = mainList.get(curr++);
if (node.left != null) {
mainList.add(node.left);
tmpList.add(node.left.val);
}
if (node.right != null) {
mainList.add(node.right);
tmpList.add(node.right.val);
}
}
}
while (!stack.empty())
list.add(stack.pop());
return list;
}
}
思路很简单,利用层次遍历,然后利用stack先进后出的思想。
十一第三题Binary Tree Level Order Traversal II
最新推荐文章于 2019-06-27 15:08:13 发布