LeetCode 236. Lowest Common Ancestor of a Binary Tree

这道题和上一道求解最低公共祖先的不同在于是一般的二叉树,只能遍历节点来获取信息

  1. 通过返回节点是否为空判定子树中是否有pq节点
  2. 三种情况
    1. p和q分别在两颗子树中:那么当前节点就是最低公共祖先
    2. p和q都在左子树:将问题转换为在当前节点的左子树找p和q的最低公共祖先
    3. p和q都在右子树:将问题转换为在当前节点的右子树找p和q的最低公共祖先
package tree.No236;

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
}

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

相关文章:

  • 2017-12-18
  • 2018-04-13
  • 2021-12-10
  • 2021-09-14
  • 2021-07-07
  • 2021-12-10
  • 2021-12-02
  • 2018-12-22
猜你喜欢
  • 2021-12-10
  • 2019-08-24
  • 2021-10-12
  • 2021-11-15
  • 2019-05-23
  • 2021-09-11
  • 2019-06-03
  • 2019-11-17
相关资源
相似解决方案