226.翻转二叉树
题目链接:226. 翻转二叉树 - 力扣(LeetCode)
很重要的一点:翻转二叉树,实质就是把每个节点的左右孩子都交换一遍。
递归要简单很多,因为要处理的和要遍历的节点是一致的,所以直接遍历就好,不用考虑额外的事情。
class Solution {
public TreeNode invertTree(TreeNode root) {
invert(root);
return root;
}
public void invert(TreeNode node) {
if (node == null) return;
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
invert(node.left);
invert(node.right);
}
}
做完以后看代码随想录的视频:到底用的是什么遍历顺序?前序,因为递归中处理节点的代码放在了前序的位置。
101. 对称二叉树(多写)
题目链接:101. 对称二叉树 - 力扣(LeetCode)
难度写的是easy,我怎么觉得这道题一点都不简单。。。
首先这道题并不是常规的二叉树遍历,要分成左右两棵子树来做。还是思考递归的三要素
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left, root.right) ;
}
public boolean compare (TreeNode left, TreeNode right) {
if (left == null && right == null) return true;
if (left == null || right == null) return false;
return left.val == right.val && compare(left.left, right.right) && compare(left.right, right.left);
}
}
104. 二叉树的最大深度
题目链接:104. 二叉树的最大深度 - 力扣(LeetCode)
首先要想明白二叉树的遍历顺序,采用后续遍历,因为要在遍历了左右子树后,比较深度。
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
111. 二叉树的最小深度
题目链接:111. 二叉树的最小深度 - 力扣(LeetCode)
这道题有迭代的思路,用层序遍历,遇到左右孩子都为空的节点,直接返回深度,不用再往下遍历了。
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Deque<TreeNode> deque = new LinkedList<>();
deque.offer(root);
int depth = 0;
while (!deque.isEmpty()) {
int size = deque.size();
depth++;
for (int i = 0; i < size; i++) {
TreeNode poll = deque.poll();
if (poll.left == null && poll.right == null) {
return depth;
}
if (poll.left != null) {
deque.offer(poll.left);
}
if (poll.right != null) {
deque.offer(poll.right);
}
}
}
return depth;
}
}
day14完结撒花~