leetcode236. 二叉树的最近公共祖先

1.题目描述:

给定一个二叉树,找到该树中两个指定节点的最近公共祖先。最近公共祖先的定义为:对于有根树T的两个节点p、q,最近公共祖先表示为一个节点x,满足x是p、q的祖先且x的深度尽可能大(一个节点也可以是它自己的祖先)。

2.路径法(存储父节点信息):

看完题目发现递归一下写不出,于是想找出p、q的遍历路径:5—>3,4—>2—>5—>3,找到这两条路径中首位相等的元素5即为最近公共祖先。关键在于如何得到该条路径并比较:借助哈希表来存储所有节点(除根节点)对应的父节点,通过哈希表自身来得到路径后借助集合(题目节点的值都不重复)存储,代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private Map<TreeNode, TreeNode> parentMap = new HashMap<>();
    private List<TreeNode> rute = new ArrayList<>();
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);        
        while (p != null) {//得到p节点到根节点的所有节点,如5到3
            rute.add(p);
            p = parentMap.get(p);
        }
        while (q != null) {//得到q节点到根节点的所有节点,如4到2到5到3
            if (rute.contains(q)) return q;//直接与p节点存储在集合中的的路径对比,有相等的直接返回
            q = parentMap.get(q);
        }
        return null;
    }

    public void dfs(TreeNode root) {//存储除去根节点外所有节点对应的父节点信息,与前中后序遍历有差别
        if (root == null) return;
        if (root.left != null) parentMap.put(root.left, root);
        if (root.right != null) parentMap.put(root.right, root);
        dfs(root.left);
        dfs(root.right);
    }
}

3.递归:

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) return root;//递归结束条件
        //后序遍历,自下而上回溯
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null && right == null) {//未找到节点p或q
            return null;
        } else if (left == null && right != null) {//只在右子树找到一个节点
            return right;
        } else if (left != null && right == null) {//只在左子树找到一个节点
            return left;
        } else {//左右子树都找到节点
            return root;
        }
    }
}

二刷:

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null && right == null) return null;
        if (left == null) return right;
        if (right == null) return left;
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值