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). " _______6______ / ___2__ ___8__ / \ /0 _4 7 9 / 3 52 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.
Idea, first determine whether the entry has illegal input.
1 if a certain root==p | | root = q, then the LCA must be root (because the top Down,lca is definitely in the root tree, and root is P q one node, then the other node must be under root, then root is the LCA), then return to root
2 if Root<min (p, Q), then the LCA must be on the right subtree, then recursion
3 if Max (P, q) <root, then the LCA must be on the left subtree, then recursion
4 if p<root<q, then root must be LCA
/** * 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) {/* if (p = = Root | | q = = Root | | root = null) {return root; } TreeNode Left=lowestcommonancestor (Root.left, p, q); TreeNode right=lowestcommonancestor (Root.right, p, q); On both sides if (left! = null && right! = null) return root; On one side if (left! = null) {} */if (Root==null | | root = = P | | root = = q) { return root; } if (Root.val < Math.min (P.val, Q.val)) {return lowestcommonancestor (Root.right, p, q); } else if (Root.val > Math.max (p.val, Q.val)) {return lowestcommonancestor (Root.left, p, q); } else {return root; }}}
Leetcode-lowest Common Ancestor of a Binary Search Tree