摘要: 题目链接 572. 另一棵树的子树 思路 判断两个树是否相等的三个条件是与的关系,即: 当前两个树的根节点值相等; 并且,s 的左子树和 t 的左子树相等; 并且,s 的右子树和 t 的右子树相等。 而判断 subRoot 是否为 root 的子树的三个条件是或的关系,即: 当前两棵树相等; 或者, 阅读全文
posted @ 2023-02-03 17:22 Frodo1124 阅读(17) 评论(0) 推荐(0) 编辑
摘要: 题目链接 104. 二叉树的最大深度 思路 递归求左右子树的最大深度并取最大值,返回值在最大值上+1。 递归终止条件为 root == null,此时返回 0。 代码 class Solution { public int maxDepth(TreeNode root) { if(root == n 阅读全文
posted @ 2023-02-03 14:33 Frodo1124 阅读(16) 评论(0) 推荐(0) 编辑
摘要: 题目链接 105. 从前序与中序遍历序列构造二叉树 思路 先序遍历的顺序是根左右,中序遍历的顺序是左根右,所以在 preorder 数组中的首元素一定是当前树的树根,再从 inorder 数组中找到这个元素的下标 index,这样 index 的左边是左子树,右边是右子树。之后再分别递归建立左右子树 阅读全文
posted @ 2023-02-03 14:28 Frodo1124 阅读(17) 评论(0) 推荐(0) 编辑
摘要: 题目链接 235. 二叉搜索树的最近公共祖先 思路 与 【DFS】LeetCode 236. 二叉树的最近公共祖先 一模一样 代码 class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, Tre 阅读全文
posted @ 2023-02-03 12:11 Frodo1124 阅读(14) 评论(0) 推荐(0) 编辑
摘要: 题目链接 236. 二叉树的最近公共祖先 思路 代码 class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p 阅读全文
posted @ 2023-02-03 10:47 Frodo1124 阅读(19) 评论(0) 推荐(0) 编辑