# 20200115 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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Given the following binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5] p = 2, q = 4 6 / \ 2 8 /\ /\ 0 4 7 9 /\ 3 5 ``` // Binary Search Tree特性,root會大於等於左邊,root會小於右邊。 // pq大於左右邊,祖先必在左 // pq小於左右邊,祖先必在右 // 反之回傳自己 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val > p.val && root.val > q.val){ return lowestCommonAncestor(root.left, p, q); } else if(root.val < p.val && root.val < q.val){ return lowestCommonAncestor(root.right, p, q); } else{ return root; } } ``` Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4] p = 5, q = 4 output: 5 3 / \ 5 1 /\ /\ 6 2 0 8 /\ 7 4 ``` /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ // 找到就先回自己,找左傳右找右傳左回自己 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) { return right; } if (right == null) { return left; } return root; } } ```