【题目1】
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。

//===================递归===================
public TreeNode invertTree(TreeNode root) {
if(root == null)
return root;
invertTree(root.left);
invertTree(root.right);
TreeNode temp;
temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
//===================迭代也一样=========
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null)
return root;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode p = stack.pop();
TreeNode temp;
temp = p.left;
p.left = p.right;
p.right = temp;
if(p.left != null)
stack.push(p.left);
if(p.right != null)
stack.push(p.right);
}
return root;
}
}
//=================层次也行===========
【题目2】
给你一个二叉树的根节点 root
, 检查它是否轴对称。
思路:两个指针,成对成对比较
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root,root);
}
public boolean compare(TreeNode left,TreeNode right){
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(left);
queue.offer(right);
while(!queue.isEmpty()){
left = queue.poll();
right = queue.poll();
if(left == null && right == null) // 判断到了空子节点
continue;
if((left==null || right == null) || left.val != right.val)
return false;
queue.offer(left.left);
queue.offer(right.right);
queue.offer(left.right);
queue.offer(right.left);
}
return true;
}
}
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
}
}
【题目3】二叉树最大深度 比较每个子树的深度,取最大深度
class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return (leftDepth>rightDepth?leftDepth:rightDepth) + 1;
}
}
【题目4】n叉树最大深度
class Solution {
public int maxDepth(Node root) {
if(root == null)
return 0;
int depth = 0;
for(Node child : root.children){
depth = Math.max(depth, maxDepth(child));
}
return depth + 1;
}
}