LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:淘宝66大促 编辑:程序博客网 时间:2024/06/15 11:53
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        if (root == null) return null;    TreeNode left = lowestCommonAncestor(root.left, p, q);    TreeNode right = lowestCommonAncestor(root.right, p, q);    if (root == p || root == q) return root;    else if ((left == p || left == q) && (right == p || right == q)) return root;    else if (left == p || left == q) return left;    else if (right == p || right == q) return right;    else return left != null ? left : right;    }}

0 0