Sakura

sakura

博客园 首页 新随笔 联系 订阅 管理

 

 

 

/**
 * 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(p.val > q.val) {
            TreeNode r = p;
            p = q;
            q = r;
        }
        while(root !=null) {
            if(root.val < p.val) {
                root = root.right;
            }else if(root.val > q.val) {
                root = root.left;
            }else{
                return root;
            }
        }
        return root;

    }
    
}

 

posted on 2020-07-14 22:50  .geek  阅读(120)  评论(0编辑  收藏  举报