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

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

问题描述:
二叉搜索数性质

  • 当前根节点值大于/等于p节点值
  • 当前根节点值小于/等于q节点值
  • 返回当前根节点
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null || p==null || q==null) {
            return null;
        }
        if(p.val>q.val) {
            TreeNode tmp = p;
            p = q;
            q = tmp;
        }
        return find(root, p, q);
    }

    public TreeNode find(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null) {
            return null;
        }
        //左
        else if(root.val>q.val) {
            return find(root.left, p, q);
        }
        //右
        else if(root.val<p.val) {
            return find(root.right, p, q);
        }
        //中
        return root;
    }
}

暴力递归
返回第一个满足条件的节点:

  • 该节点左子树中包含p
  • 该节点右子树中包含q

执行用时:7 ms, 在所有 Java 提交中击败了39.70%的用户
内存消耗:40.4 MB, 在所有 Java 提交中击败了5.05%的用户

class Solution {
    private TreeNode target;

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        find(root, p, q);
        return target;
    }

    public boolean[] find(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null || targt!=null) {
            return new boolean[]{false, false};
        }
        
        boolean[] res = new boolean[2];
        res[0] = root==p? true: false;
        res[1] = root==q? true: false;

        boolean[] res1 = find(root.left, p, q);
        boolean[] res2 = find(root.right, p, q);
        res[0] |= res1[0] | res2[0];
        res[1] |= res1[1] | res2[1];
        if(target==null && res[0]&res[1]) {
            target = root;
        }

        return res;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13742282.html