力扣爆刷第90天之hot100五连刷36-40
文章目录
- 力扣爆刷第90天之hot100五连刷36-40
- 一、94. 二叉树的中序遍历
- 二、104. 二叉树的最大深度
- 三、26. 翻转二叉树
- 四、101. 对称二叉树
- 五、543. 二叉树的直径
一、94. 二叉树的中序遍历
题目链接:https://leetcode.cn/problems/binary-tree-inorder-traversal/description/?envType=study-plan-v2&envId=top-100-liked
思路:最简单的中序遍历,无需多说。
class Solution {List<Integer> list = new ArrayList<>();public List<Integer> inorderTraversal(TreeNode root) {order(root);return list;}void order(TreeNode root) {if(root == null) {return ;}order(root.left);list.add(root.val);order(root.right);}
}
二、104. 二叉树的最大深度
题目链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/?envType=study-plan-v2&envId=top-100-liked
思路:后续遍历到根节点,选取左右子树的结果中的最大值作为子树深度,然后加1即本节点,返回。
class Solution {public int maxDepth(TreeNode root) {if(root == null) {return 0;}int left = maxDepth(root.left);int right = maxDepth(root.right);return Math.max(left, right) + 1;}
}
三、26. 翻转二叉树
题目链接:https://leetcode.cn/problems/invert-binary-tree/description/?envType=study-plan-v2&envId=top-100-liked
思路:前序遍历,然后逐个交换节点左右子树即可。
class Solution {public TreeNode invertTree(TreeNode root) {order(root);return root;}void order(TreeNode root) {if(root == null) return ;TreeNode t = root.left;root.left = root.right;root.right = t;order(root.left);order(root.right);}}
四、101. 对称二叉树
题目链接:https://leetcode.cn/problems/symmetric-tree/description/?envType=study-plan-v2&envId=top-100-liked
思路:判断是否是对称二叉树,直接把根节点的左右子树,作为一颗树进行遍历。
class Solution {public boolean isSymmetric(TreeNode root) {return isEquels(root.left, root.right);}boolean isEquels(TreeNode child1, TreeNode child2) {if(child1 == null && child2 == null) return true;if((child1 == null && child2 != null) || (child1 != null && child2 == null)) return false;if(child1.val != child2.val) return false;return isEquels(child1.left, child2.right) && isEquels(child1.right, child2.left);}
}
五、543. 二叉树的直径
题目链接:https://leetcode.cn/problems/diameter-of-binary-tree/description/?envType=study-plan-v2&envId=top-100-liked
思路:其实求的就是任意一个节点其左右子树能够连接的最长边长,那么问题就转化为求每个节点左子树的最长路径和右子树的最长路径和。
class Solution {int max = 0;public int diameterOfBinaryTree(TreeNode root) {order(root);return max;}int order(TreeNode root) {if(root == null) return 0;int left = order(root.left);int right = order(root.right);max = Math.max(max, left + right);return Math.max(left, right) + 1;}}