-
Notifications
You must be signed in to change notification settings - Fork 639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
leetcode236:二叉树的最近公共祖先 #43
Comments
解答:递归实现解题思路: 如果树为空树或 如果不是,即二叉树不为空树,且
代码实现: const lowestCommonAncestor = function(root, p, q) {
if(root == null || root == p || root == q) return root
const left = lowestCommonAncestor(root.left, p, q)
const right = lowestCommonAncestor(root.right, p, q)
if(left === null) return right
if(right === null) return left
return root
}; 复杂度分析: 时间复杂度:O(n) 空间复杂度:O(n) |
const lowestCommonAncestor=function(root,p,q){
if(root==null || root==p || root==q){
return root
}
const left=lowestCommonAncestor(root.left,p,q);
const right=lowestCommonAncestor(root.right,p,q);
if(left==null) return right;
if(right==null) return left;
return root;
} |
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
if(root == null || root == p || root == q){
return root;
}
let left = lowestCommonAncestor(root.left,p,q);
let right = lowestCommonAncestor(root.right,p,q);
if(left != null && right != null){
return root;
}
return left != null ? left : right;
}; |
var lowestCommonAncestor = function (root, p, q) {
function isInTree(root, node) {
if (root === null) return false;
if (root === node) return true;
return isInTree(root.left, node) || isInTree(root.right, node);
}
let current = root;
while (true) {
if (current === p || current === q) return current;
if (isInTree(current.left, p)) {
if (isInTree(current.right, q)) {
return current;
} else {
current = current.left;
}
} else {
if (isInTree(current.left, q)) {
return current;
} else {
current = current.right;
}
}
}
}; |
这思路是怎么想到的,有什么可迁移的方法套路嘛 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:
示例 2:
说明:
附赠leetcode地址:leetcode
The text was updated successfully, but these errors were encountered: