• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Leetcode 107: level traversal of binary tree II (Java)

King Wang

1 月 3, 2022

LeetCode 107: The level traversal of binary tree II(java)

subject :

answer :

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> res=new ArrayList<>();
Stack<List<Integer>> stack=new Stack<>();
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root==null)
return res;
TreeNode nodeTemp=root;
Queue<TreeNode> nodeQueue=new LinkedList<>();
nodeQueue.add(nodeTemp);
while(!nodeQueue.isEmpty()){
int length=nodeQueue.size();
List<Integer> list =new ArrayList<>();
for(int i=0;i<length;i++){
nodeTemp=nodeQueue.poll();
list.add(nodeTemp.val);
if(nodeTemp.left!=null)
nodeQueue.add(nodeTemp.left);
if(nodeTemp.right!=null)
nodeQueue.add(nodeTemp.right);
}
stack.push(list);
}
while(!stack.isEmpty()){
res.add(stack.pop());
}
return res;
}
}

 

发表回复