二叉搜索树最近公共祖先

44 阅读1分钟

//leetcode submit region begin(Prohibit modification and deletion) /**

  • Definition for a binary tree node.
  • public class TreeNode {
  • int val;
    
  • TreeNode left;
    
  • TreeNode right;
    
  • TreeNode(int x) { val = x; }
    
  • } */

class Solution { public TreeNode lowestCommonAncestor(TreeNode node, TreeNode p, TreeNode q) { if(node == null){ return null; }

    TreeNode left = null;
    //当前节点值大于俩目标节点的值,则将当前节点值的左孩子传入内层递归,继续寻找
    if(node.val < p.val && node.val < q.val){
        left = lowestCommonAncestor(node.right, p, q);
        //不为null则表示内层递归找到结果,直接向外层抛出结果
        if(left != null) {
            return left;
        }
    }

    TreeNode right = null;
    //当前节点值小于俩目标节点的值,则将当前节点值的右孩子传入内层递归,继续寻找
    if(node.val > p.val && node.val > q.val){
        right = lowestCommonAncestor(node.left, p, q);
        //不为null则表示内层递归找到结果,直接向外层抛出结果
        if(right != null){
            return right;
        }
    }

    //当前节点值恰好为俩目标值中间,则找到
    return node;
}

}

本文由博客一文多发平台 OpenWrite 发布!