Leetcode 236. Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:虚拟机 ubuntu 屏幕 编辑:程序博客网 时间:2024/04/30 06:33
原题:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
题目大意:已知一个BT,找到BST中的节点p+q的最小公共祖先;
例子:
        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4
5,1 -> 3
5,4 -> 5 (允许一个node成为自己的descendant)

思路:
1 boundary conditions: root, p, q任意为null, 返回null
2 查看左子树中是否有目标结点,没有为null
3 都不为空,说明做右子树都有目标结点,则公共祖先就是本身

4 如果有一个为null, 返回另外一个;用三目表达式;


/** * Definition for a binary tree node. * public class TreeNode { *     public int val; *     public TreeNode left; *     public TreeNode right; *     public TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        //发现目标节点则通过返回值标记该子树发现了某个目标结点        if(root == null || root == p || root == q)            return root;        //查看左子树中是否有目标结点,没有为null        TreeNode left = LowestCommonAncestor(root.left, p, q);        //查看右子树是否有目标节点,没有为null        TreeNode right = LowestCommonAncestor(root.right, p, q);                //都不为空,说明做右子树都有目标结点,则公共祖先就是本身        if(left!=null&&right!=null) return root;                //如果发现了目标节点,则继续向上标记为该目标节点        return left == null ? right : left;    }}


0 0