235. 二叉搜索树的最近公共祖先
- 原题链接:
- 完成情况:
- 解题思路:
- _235二叉搜索树的最近公共祖先_递归
- _235二叉搜索树的最近公共祖先_简洁递归
- 参考代码:
- 错误经验吸取
原题链接:
235. 二叉搜索树的最近公共祖先
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
完成情况:
解题思路:
_235二叉搜索树的最近公共祖先_递归
package 代码随想录.树.二叉树;import 代码随想录.树.TreeNode;public class _235二叉搜索树的最近公共祖先_递归 {/**** @param root* @param p* @param q* @return*/public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if (root == null || root == p || root == q){return root;}// 后序遍历TreeNode leftNode = lowestCommonAncestor(root.left, p, q);TreeNode rightNode = lowestCommonAncestor(root.right, p, q);//从下往上找,先到最底层if (leftNode == null && rightNode == null){return null;} else if (leftNode != null && rightNode == null) {return leftNode;} else if (rightNode != null && leftNode == null) {return rightNode;}else { // rightNode != null 并且 leftNode != nullreturn root;}}
}
_235二叉搜索树的最近公共祖先_简洁递归
package 代码随想录.树.二叉树;import 代码随想录.树.TreeNode;public class _235二叉搜索树的最近公共祖先_简洁递归 {/**** @param root* @param p* @param q* @return*/public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if (root.val > p.val && root.val > q.val) {return lowestCommonAncestor(root.left,p,q);}if (root.val < p.val && root.val < q.val){return lowestCommonAncestor(root.right,p,q);}return root; // 如果当前检测到p,q不在同一侧,那么必然当前root就是最近父节点}
}