阅读 114

leetcode 236 而哈数的最近公共祖先

leetcode 236 而哈数的最近公共祖先

简介

dfs 找出路劲,然后长链在短链里面找.

code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */class Solution {public:    int level = 0;    vector<TreeNode*> path1;    vector<TreeNode*> path2;    bool dfs(TreeNode *n, vector<TreeNode*> &path, TreeNode *p){        if(n == p){
            path.push_back(n);            return true;
        }        if(n->left){            if(dfs(n->left, path, p)){
                path.push_back(n);                return true;
            }
        }        if(n->right){            if(dfs(n->right, path, p)){
                path.push_back(n);                return true;
            }
        }        return false;
    }    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root, path1, p);
        dfs(root, path2, q);        // 长链在短链找
        if(path1.size() >= path2.size()){            int i=0;            while(i<path1.size()){                if(find(path2.begin(), path2.end(), path1[i])!= path2.end()){                    return path1[i];
                }
                i++;
            }
        }        else{            int i= 0;            while(i<path2.size()){                if(find(path1.begin(), path1.end(), path2[i])!= path1.end()){                    return path2[i];
                }
                i++;
            }
        }        return nullptr;
    }
};
class Solution {    private TreeNode ans;    public Solution() { // 使用公共变量记得在构造函数中初始化
        this.ans = null;
    }    private boolean dfs(TreeNode root, TreeNode p, TreeNode q){        if(root == null) return false;
        bool lson = dfs(root.left, p, q);
        bool rson = dfs(root.right, p, q);        if((lson && rson) || ((root.val == p.val || root.val == q.val) && (lson || rson))) {
            ans = root;
        }        return lson || rson || (root.val == p.val || root.val == q.val));
    }    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        this.dfs(root, p, q);        return this.ans;
    }
}

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne

服务器评测 http://www.cncsto.com/ 

服务器测评 http://www.cncsto.com/ 


文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐