首页 > 技术文章 > leetcode 235. Lowest Common Ancestor of a Binary Search Tree

infoflow 2017-08-28 00:04 原文

知识点:

两个节点的最近公共祖先

思路:

用dfs从根节点往下搜索节点,用栈记录从根节点到该节点之间的所有节点。由于栈的先进后出特性,我们就能得到该节点到根节点的序列。

两个节点的最近公共祖先就是各自往上回溯祖先时的第一个相同的节点。
由于两个节点到公共祖先的距离不一样,所以两个栈的大小不一样。先计算栈大小的差值,然后将元素多的那个栈的节点先弹出几个节点。接下来两个栈的栈顶元素到公共祖先的距离就是一样了。两个栈同时弹出元素,直到找到共通祖先。


class Solution {

    private Stack<TreeNode> pPath=new Stack<>();
    private Stack<TreeNode> qPath=new Stack<>();
    public boolean dfs(TreeNode root,TreeNode t,Stack<TreeNode> s){

        if(root !=null){
            if(root.val ==t.val){
                return true;
            }else {
                s.push(root.left);
                if(dfs(root.left,t,s)) {
                    return true;
                }else {
                    s.pop();
                }
                s.push(root.right);
                if(dfs(root.right,t,s)){
                    return true;
                }else {
                    s.pop();
                }
                return false;
            }
        }

        return false;
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        pPath.push(root );
        dfs(root,p,pPath);
        qPath.push(root );
        dfs(root,q,qPath);
        int h;
        if(pPath.size() > qPath.size()){
            h=pPath.size() - qPath.size();
            for(int i=0;i<h;++i){
                pPath.pop();
            }
        }else {
            h=qPath.size() - pPath.size();
            for(int i=0;i<h;++i){
                qPath.pop();
            }
        }
        h=qPath.size();
        TreeNode result = null;
        for(int i=0;i<h;++i){
            if(qPath.peek() == pPath.peek()){
                result= qPath.peek();
                break;
            }else {
                qPath.pop();
                pPath.pop();
            }
        }
        return result;
    }
}

推荐阅读