Leetcode 4.28 Tree Easy

时间:2022-11-09 18:13:45

1. 101. Symmetric Tree

  用递归。

 class Solution {
public boolean isSymmetric(TreeNode root) {
if( root == null)
return true;
return symmetric(root.left, root.right);
} public boolean symmetric(TreeNode p, TreeNode q){
if(p == null || q == null)
return p == q? true:false;
return p.val == q.val && symmetric(p.left, q.right) && symmetric(p.right, q.left);
}
}

2. 107. Binary Tree Level Order Traversal II

    list表示当前层的所有节点,nextList表示下一层的所有节点。

 class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList();
List<TreeNode> list = new ArrayList();
if( root == null)
return res;
list.add(root); while(!list.isEmpty()){
List<Integer> curList = new ArrayList();
List<TreeNode> nextList = new ArrayList();
for(TreeNode cur: list){ //循环当前层
curList.add(cur.val);
if(cur.left != null) nextList.add(cur.left);
if(cur.right != null) nextList.add(cur.right);
}
list = nextList;
res.add(0, curList);
}
return res;
}
}