Topic:
Given A binary search tree (BST), find the lowest common ancestor (LCA) of the Given nodes in the BST.
According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have both V and W as descendants (where we allow a node to be a descendant of itself). "
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 are 2, since a node can be a descendant of itself according to the LCA definition.
Translation:
Given a search binary tree, find the smallest common ancestor (LCA) for a given 2 nodes.
According to Wikipedia's definition of LCA, the smallest common ancestor is a minimum node defined in the tree T, which satisfies the other 2 nodes in the tree V and W are its descendants (here we allow one to be its own offspring).
For example, the LCA in 2 and 8 is 6,2 and 4 of the LCA is 2.
Analysis:
The idea of this problem is from the root node of the common ancestor of the node start, according to the nature of the search binary tree, that is, any node of the left subtree of all nodes of the value must be smaller than the node, the right subtree will be larger than the node, a step to find the smallest common ancestor.
If you traverse to a node, the value of the 2 subtrees tree is neither smaller than the node, nor is it larger than the node, there are only 2 possibilities: the first may be a value of 2 subtrees tree, one larger than the node, and one smaller than the node; the other one may have at least one subtree that is equal to that node. Either way, the smallest common ancestor at this time is the node.
Code:
/** * Definition for a binary tree node. * public class TreeNode {* Int. val; * TreeNode left; * TreeNode Right * TreeNode (int x) {val = x;}} * *Public class solution {Public TreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {TreeNode lca=root; while(true){if(p.Val<lca.Val&&q.Val<lca.Val) {lca=lca.left; }Else if(p.Val>lca.Val&&q.Val>lca.Val) {lca=lca.right; }Else{ Break; } }returnLCA; }}
Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty:easy]