难度中等1512
给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Deque<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new LinkedList<>();
if(root == null)return res;
List<Integer> tmp ;
queue.offerLast(root);
while(queue.size() != 0){
tmp = new LinkedList<>();
int size = queue.size();
for(int i =0;i < size;i++){
TreeNode node = queue.pollFirst();
tmp.add(node.val);
if(node.left != null)queue.offerLast(node.left);
if(node.right != null)queue.offerLast(node.right);
}
res.add(tmp);
}
return res;
}
}
难度简单1446
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
class Solution {
public TreeNode invertTree(TreeNode root) {
//迭代前序
Deque<TreeNode> s = new LinkedList<>();
TreeNode cur = root;
while(!s.isEmpty() || cur != null){
if(cur != null){
//前序节点
s.push(cur);
TreeNode tmp = cur.right;
cur.right = cur.left;
cur.left = tmp;
cur = cur.left;
}else{
cur = s.pop().right;
}
}
return root;
}
}
class Solution {
public TreeNode invertTree(TreeNode root) {
//前
if(root == null)return null;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
难度简单2187收藏分享切换为英文接收动态反馈
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
class Solution {
public boolean isSymmetric(TreeNode root) {
return process(root,root);
}
public boolean process(TreeNode p,TreeNode q ){
if(p == null && q == null)return true;
if(p == null || q == null)return false;
if(p.val != q.val)return false;
return process(p.left,q.right) && process(p.right,q.left);
}
}