剑指offer_树中两个节点的最低公共祖先

一、是二叉树,并且是二叉搜索树。

二叉查找树中,两个节点 p, q 的公共祖先 root 满足 root.val >= p.val && root.val <= q.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 public class Solution {
11     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12         if(root==null||root==p||root==q)
13             return root;
14         if(root.val>p.val&&root.val>q.val)
15             return lowestCommonAncestor(root.left,p,q);
16         if(root.val<p.val&&root.val<q.val)
17             return lowestCommonAncestor(root.right,p,q);
18         else
19             return root;
20     }
21 }

 

普通二叉树

 1 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
 2         if(root==null||root==p||root==q)
 3             return root;
 4         TreeNode left = lowestCommonAncestor(root.left,p,q);
 5         TreeNode right = lowestCommonAncestor(root.right,p,q);
 6         if (left == null) 
 7             return right;
 8         if (right == null) 
 9             return left;
10         return root;
11     }

 

posted @ 2019-09-19 09:47  chyblogs  阅读(144)  评论(0)    收藏  举报