**LeetCode-Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:linux grep命令与管道 编辑:程序博客网 时间:2024/05/24 00:10

假如访问到一点 等于其中某一个node 那就返回这个node

都不等于就分别访问左右子树 左右两边假如返回的都不是null 那么lca就是root

假如一个是null 那lca就是另一个

其实还没想清楚

public 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 ? left : right;    }}


0 0
原创粉丝点击