LCA-最近公共祖先

方法一、dfs

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode res;

    public Solution() { //构造函数
        this.res = null;
    }
    
    public boolean dfs(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return false;
        
        boolean lson = dfs(root.left, p, q);    //深搜,先在左子树里找;
        boolean rson = dfs(root.right, p, q);    //深搜,再在右子树里找
        
        if((lson && rson) || ((root.val == p.val || root.val == q.val) && (lson || rson))) {
            res = root;
        }
    
        return lson || rson || (root.val == p.val || root.val == q.val);//返回的结果表示,当前节点的子树(包括节点本身)是否包含p或者q
    }
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        this.dfs(root, p, q);
        return this.res;
    }
}

 

方法二、HashMap

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

 /*所有节点的值都是唯一的
 * LCA 求最近公共祖先
 * 先从根节点遍历二叉树,存储每个节点的父亲节点的信息
 * 然后从p出发,用vis记录其祖先
 * 最后从q出发,判断vis中是否也包含q的祖先,如果有直接返回答案,返回的结果就是最近的公共祖先
 * */

class Solution {
    Map<Integer, TreeNode> par = new HashMap<>();
    Set<Integer> vis =     new HashSet<>();    
    
    public void dfs(TreeNode root) {    //dfs存储每个节点的父亲节点的信息
        if(root.left != null) {
            par.put(root.left.val, root);
            dfs(root.left);
        }
        
        if(root.right != null) {
            par.put(root.right.val, root);
            dfs(root.right);
        }
    }
    
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);
        
        while(p != null) {
            vis.add(p.val);
            p = par.get(p.val);
        }
        
        while(q != null) {
            if(vis.contains(q.val)) {
                return q;
            }
            q = par.get(q.val);
        }
        
        return null;
    }
}

 

posted @ 2020-09-26 10:43  Peterxiazhen  阅读(107)  评论(0编辑  收藏  举报