235. 二叉搜索树的最近公共祖先

题目链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/submissions/

解题思路:

如果p和q都小于root,去左边找就行。

如果p和q在两侧的,直接就是root,这个可以通过val来判断。

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12         if(root==null||root==p||root==q)
13         {
14             return root;
15         }
16         if(p.val<root.val && q.val<root.val)
17         {
18             return lowestCommonAncestor(root.left,p,q);
19         }
20         else if(p.val>root.val && q.val>root.val)
21         {
22             return lowestCommonAncestor(root.right,p,q);
23         }
24         else
25         {
26             return root;
27         }
28     }
29 }
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/11240619.html