LeetCode 236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

找到二叉树中最近的公共节点比在搜索二叉树中寻找要难一些
没做出来,看了网上解答明悟

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(root == null || root == p || root == q) return root;
            TreeNode left = lowestCommonAncestor(root.left,p,q);
            if(left != p && left != q && left != null) return left;
            TreeNode right = lowestCommonAncestor(root.right,p,q);
            if(left != null && right != null) return root;
            return left == null ? right : left;
    }

这个递归其实并不是那么完美解释题意,因为当p q不在当前树中的节点中时,比如只存在q,那么也会返回q,其实应该要返回null,但由于我们又要知道左右的子树中是否含有p 或者 q 就必须要存在即返回。

如果题中加一个条件:如果p或q不存在树中则返回null难度就更大了

需要为每一个当前节维护一个计数器,记录它的子节点中存在p 或 q的个数 java中引用传递真的很麻烦,所以就用了数组来代替值做引用传递了

个人认为这样才是最终完美的答案

 public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        List<TreeNode> list = new ArrayList<>();
        return lowestCommonAncestor2(root, p, q, new int[]{0});
    }


    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q, int[] count) {
        int[] countNow = new int[]{0};
        if (root == null || count[0] == 2) return null;
        if (root == p || root == q) {
            countNow[0]++;
            if (count[0] == 2) return null;
        }

        TreeNode left = lowestCommonAncestor2(root.left, p, q, countNow);
        TreeNode right = lowestCommonAncestor2(root.right, p, q, countNow);
        count[0] = countNow[0] + count[0];
        if (countNow[0] != 2) return null;
        if (left == null && right == null) return root;
        return left == null ? right : left;


    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值