leetcode235 - Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST),find the lowest common ancestor (LCA) of two given nodes in the BST. Example 1: ? 利用BST特性。 ? 实现: /** * 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.val == p.val || root.val == q.val) { return root; } if (root.val > p.val && root.val < q.val || root.val < p.val && root.val > q.val) { return root; } TreeNode left = lowestCommonAncestor(root.left,p,q); TreeNode right = lowestCommonAncestor(root.right,q); return left != null ? left : right; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |