前言 📢
本日记为个人的刷题学习日记,内容非原创,仅为自己复习知识时,能够看得懂自己写的CV的代码,快速理解题意。另外,👍力扣官方的题解很好用,三叶姐nb!!!!!
104. 二叉树的最大深度 ✅
题意
- 给你一个二叉树的根结点
root
,判断该树的深度(层数)
思路
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { public int maxDepth(TreeNode root) { if(root == null) { return 0; } else { int left = maxDepth(root.left); int right = maxDepth(root.right); return Math.max(left, right) + 1; } } }
|
98. 验证二叉搜索树 ✅
题意
思路
中序遍历(二叉搜索树中序遍历后,得到的是一组严格递增的数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { long pre = Long.MIN_VALUE; public boolean isValidBST(TreeNode root) {
if(root == null) { return true; } if(!isValidBST(root.left)) { return false; } if(root.val <= pre) { return false; } pre = root.val;
return isValidBST(root.right); } }
|
101.对称二叉树 ✅
题意
思路
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
class Solution { public boolean isSymmetric(TreeNode root) { return dfs(root, root); }
public boolean dfs(TreeNode rootLeft, TreeNode rootRight) { if(rootLeft == null && rootRight == null) { return true; }
if(rootLeft == null || rootRight == null || rootLeft.val != rootRight.val) { return false; } else { return dfs(rootLeft.left, rootRight.right) && dfs(rootLeft.right, rootRight.left); } } }
|