- leetcode BFS+DFS
- Leetcode PHP题解--D125 107. Binary
- leetcode:107. Binary Tree Level
- 107. Binary Tree Level Order Tra
- Binary Tree Zigzag Level Order T
- Leetcode-103题:Binary Tree Zigzag
- [Leetcode] 88. Binary Tree Zigza
- [Leetcode] 73. Binary Tree Zigza
- 107. Binary Tree Level Order Tra
- Q107 Binary Tree Level Order Tra
因为要求bottom-up 可以考虑使用一个stack。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if(root==null)return result;
Stack<List<Integer>> stack = new Stack<>();
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while(!queue.isEmpty())
{
int size = queue.size();
List<Integer> list = new ArrayList<>();
for(int i = 0 ;i<size;i++)
{
TreeNode node = queue.poll();
list.add(node.val);
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
}
stack.push(list);
}
while(!stack.isEmpty())
{
result.add(stack.pop());
}
return result ;
}
}
网友评论