Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:虚拟机 ubuntu 屏幕 编辑:程序博客网 时间:2024/04/30 06:08
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
题目大意:已知一个BST,找到BST中的节点p+q的最小公共祖先;
思路:递归
1 boundary conditions: tree, p, q任意为null, 返回null
2 如果p.va, q.val均小于root.val -> 说明p,q都在左子树-> return LowestCommonAncestor(root.left, p, q);

3  如果p.va, q.val均大于root.val -> 说明p,q都在右子树-> return LowestCommonAncestor(root.right, p, q);

4 否则,说明一左一右->root即为最小公共祖先

/** * Definition for a binary tree node. * public class TreeNode { *     public int val; *     public TreeNode left; *     public TreeNode right; *     public TreeNode(int x) { val = x; } * } */


 public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {         if (p == null || q == null || root == null)            {                return null;            }            if (p.val < root.val && q.val < root.val)            {                return LowestCommonAncestor(root.left, p, q);            }            else if (p.val > root.val && q.val > root.val)            {                return LowestCommonAncestor(root.right, p, q);            }            else            {                return root;            }    }


0 0
原创粉丝点击