Shu-How Zの小窝

Loading...

235.二叉搜索树的最近公共祖先

/**
 * 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) {
    let temp=root;
    while(true){
		// 如果小于根 都在左边
        if(temp.val>p.val&&temp.val>q.val){
           return  lowestCommonAncestor(root.left,p,q);
        }
        else if(temp.val<p.val&&temp.val<q.val){
           return lowestCommonAncestor(root.right,p,q);
        }
        else{
            break;
        }
    }
    return temp;
};

解决普遍二叉树的最近公共祖先问题。

潜在问题

  1. 递归调用错误:在 while 循环中,你错误地使用了 root.leftroot.right 而不是 temp.lefttemp.right
  2. 无限循环风险:如果 pq 不在树中,代码可能会陷入无限循环。
  3. 边界条件:没有处理 rootnull 的情况。
  4. 逻辑错误:在普遍二叉树中,不能仅依赖节点值来判断方向,需要使用其他方法来找到最近公共祖先。

优化建议

  1. 修正递归调用:确保递归调用使用正确的节点。
  2. 处理边界条件:增加对 rootnull 的检查。
  3. 实现普遍二叉树的最近公共祖先:使用递归方法来查找最近公共祖先。

改进后的代码

以下是改进后的代码,适用于普遍二叉树的最近公共祖先问题:

/**
 * 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) {
        return null;
    }
    
    if (root === p || root === q) {
        return root;
    }
    
    const left = lowestCommonAncestor(root.left, p, q);
    const right = lowestCommonAncestor(root.right, p, q);
    
    if (left !== null && right !== null) {
        return root;
    }
    
    return left !== null ? left : right;
};

解释

  1. 边界条件:首先检查 root 是否为 null,如果是,则返回 null
  2. 匹配节点:如果 root 等于 pq,则返回 root
  3. 递归查找:分别在左子树和右子树中查找 pq
  4. 返回结果:如果在左子树和右子树中都找到了 pq,则 root 是最近公共祖先。否则,返回找到的非空节点。

这样改进后的代码可以正确处理普遍二叉树的最近公共祖先问题,并且避免了潜在的风险和逻辑错误。

posted @ 2024-12-28 20:10  KooTeam  阅读(40)  评论(0)    收藏  举报