码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 235: Lowest Common Ancestor of a Binary Search Tree

时间:2017-12-03 12:55:33      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:init   mon   target   http   another   pre   desc   sea   root   

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /                  ___2__          ___8__
   /      \        /         0      _4       7       9
         /           3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

 

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public 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) return null;
13         
14         if (p.val < root.val && q.val < root.val)
15         {
16             return LowestCommonAncestor(root.left, p, q);
17         }
18         else if (p.val > root.val && q.val > root.val)
19         {
20             return LowestCommonAncestor(root.right, p, q);
21         }
22         
23         return root;
24     }
25 }
26 
27 // it work for any binary tree including BST
28 public class Solution1 {
29     private bool LCA(TreeNode root, TreeNode p, TreeNode q, bool[] found)
30     {
31         if (root == p)
32         {
33             found[0] = true;
34         }
35         
36         if (root == q)
37         {
38             found[1] = true;
39         }
40         
41         if (found[0] && found[1]) return true;
42         if (root == null) return false;
43         
44         return LCA(root.left, p, q, found) || LCA(root.right, p, q, found);
45     }
46     
47     public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
48         if (root == null) return null;
49         
50         if (LCA(root.left, p, q, new bool[2]))
51         {
52             return LowestCommonAncestor(root.left, p, q);
53         }
54         else if (LCA(root.right, p, q, new bool[2]))
55         {
56             return LowestCommonAncestor(root.right, p, q);
57         }
58         
59         return root;
60     }
61 }

 

 
 
 

Leetcode 235: Lowest Common Ancestor of a Binary Search Tree

标签:init   mon   target   http   another   pre   desc   sea   root   

原文地址:http://www.cnblogs.com/liangmou/p/7965716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!