-
BingoPython:迭代法
class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): while (p.val - root.val) * (q.val - root.val) > 0: root = [root.left, root.right][p.val > root.val] return root
-
BingoPython:递归法
class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): if (p.val - root.val) * (q.val - root.val) <= 0: return root elif p.val < root.val: return self.lowestCommonAncestor(root.left, p, q) else: return self.lowestCommonAncestor(root.right, p, q)
-
BingoJava:迭代法
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while ((root.val - p.val) * (root.val - q.val) > 0) root = p.val < root.val ? root.left : root.right; return root; }
-
BingoJava:递归法
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { return (root.val - p.val) * (root.val - q.val) < 1 ? root : lowestCommonAncestor(p.val < root.val ? root.left : root.right, p, q); }
-
BingoC++:迭代法
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* cur = root; while (true) { if (p -> val < cur -> val && q -> val < cur -> val) cur = cur -> left; else if (p -> val > cur -> val && q -> val > cur -> val) cur = cur -> right; else return cur; } } };
-
BingoC++:递归法
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (p -> val < root -> val && q -> val < root -> val) return lowestCommonAncestor(root -> left, p, q); if (p -> val > root -> val && q -> val > root -> val) return lowestCommonAncestor(root -> right, p, q); return root; } };
-