Test instructions: For a binary sorting tree, find the LCA of P and Q.
Idea: Given is a sort of tree, then each node must be greater than the largest in the left subtree, less than the smallest of the right sub-tree species. Based on this feature, it is much easier to find a LCA.
Three types of cases:
(1) P and Q are both on the left side of root, then the root Zuozi recursion.
(2) on the right side.
(3) One left and one right, then the root->val is certainly greater than 1 of them, less than the other.
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: ATreenode* lowestcommonancestor (treenode* root, treenode* p, treenode* q) {//This is a sort of tree ah! - if((root->val-p->val) * (root->val-q->val) <=0)//a big one will produce negative, or root for 1 of them, then 0 - returnRoot; the if(Max (P->val, Q->val) < Root->val)//all on the left . - returnLowestcommonancestor (root->Left , p, q); - Else //all on the right . - returnLowestcommonancestor (root->Right , p, q); + } -};
AC Code
Leetcode Lowest Common Ancestor of a Binary Search Tree (LCA recent public ancestor)