/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
if(root==null)
return lists;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
int n = q.size();
ArrayList<Integer> list = new ArrayList<>();
while(n>0){
TreeNode temp = q.poll();
list.add(temp.val);
if(temp.left!=null)
q.add(temp.left);
if(temp.right!=null)
q.add(temp.right);
n--;
}
lists.add(list);
}
for(int i=0;i<lists.size()/2;i++){
ArrayList<Integer> temp = lists.get(i);
lists.set(i,lists.get(lists.size()-i-1));
lists.set(lists.size()-i-1,temp);
}
return lists;
}
}
将二叉树从叶节点到根节点输出
最新推荐文章于 2022-11-19 17:18:28 发布