Algorithms—235.Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:表格中数据怎么求和 编辑:程序博客网 时间:2024/06/06 07:40

思路:二叉搜索树,直接判断p.val和q.val于root.val的大小,如果同向,则同侧继续判断,如果不同向,则返回root。

/** * 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 (root==p) {return p;}    if (root==q) {return q;}        int ip=root.val-p.val;        int iq=root.val-q.val;        if (ip>0!=iq>0) {        return root;}else {if (ip>0) {return lowestCommonAncestor(root.left,p,q);}else {return lowestCommonAncestor(root.right,p,q);}}    }}



0 0
原创粉丝点击