【题目1】
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
![](https://img-blog.csdnimg.cn/ba14bd3f3ba04701a1e8d5e3bf971bef.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6L2v5Lq65a2mamF2YQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
//===================递归===================
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;
}
}
【题目5】求最小深度
给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。说明: 叶子节点是指没有子节点的节点。
![](https://img-blog.csdnimg.cn/de17e4df878b4c0e80b230a04de6065c.png)
class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if(leftDepth == 0)
return rightDepth+1;
if(rightDepth==0)
return leftDepth+1;
return Math.min(leftDepth,rightDepth)+1;
}
}