算法 - 树最小公共节点

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/

 

一开始没仔细看题目是搜索树,写的是普通二叉树的解法:

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode result = null;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        findNode(root,p,q);
        return result;
    }
    
    
    public int findNode(TreeNode root, TreeNode p, TreeNode q)
    {
        if(root==null || result !=null) return 0;
        int lv = findNode(root.left,p,q);
        int rv = findNode(root.right,p,q);
        if(result!=null) return 0;
        if(root==p)
        {
            if(lv+rv==2) result = p;
            return 1;
        }
        if(root==q)
        {
            if(lv+rv==1) result = q;
            return 2;
        }
        if(lv + rv ==3) result = root;
        return lv+rv;
    }
}

 

搜索树就简单很多了:

/**
 * 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) return null;
        if(p.val < q.val)
        {
            if(root.val > q.val) return lowestCommonAncestor(root.left,p,q);
            else if(root.val < p.val) return lowestCommonAncestor(root.right,p,q);
            else return root;
        }
        else return lowestCommonAncestor(root,q,p);
    }
}

 

转载于:https://www.cnblogs.com/qlky/p/7883792.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值