【无标题】

文章提供了两种方法来寻找二叉树中两个给定节点的最低公共祖先。方法1使用深度优先搜索(DFS),方法2通过迭代并保存每个节点的父节点。在DFS方法中,递归地检查节点及其子节点,当找到p和q时返回最近公共祖先。而在迭代方法中,先遍历整个树构建父节点映射,然后从p和q开始回溯至公共祖先。
摘要由CSDN通过智能技术生成

方法1:dfs

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode res;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        boolean flag = help(root, p, q);
        return res;
    }

    public boolean help(TreeNode root, TreeNode p, TreeNode q){
        if(root == null){
            return false;
        }
        boolean left = help(root.left, p, q);
        boolean right = help(root.right, p ,q);
        if(left && right || (root==p && (left || right)) || (root==q &&(left || right))){ //如果当前节点的左子树和右子树分别存在p和q,p和q之一为当前节点,则当前节点为其最近祖先
            res = root;
            return true;
        }
        return root==p || root==q || left || right;
    }
}

方法2:迭代保存父节点

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    //迭代保存parent节点
    Map<TreeNode, TreeNode> parents = new HashMap<>();
    Set<TreeNode> visit = new HashSet<>();
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);
        while(p!=null){
            visit.add(p);
            p = parents.get(p);
        }
        while(q!=null){
            if(visit.contains(q)){
                return q;
            }
            q = parents.get(q);
        }
        return null;
    }

    public void dfs(TreeNode root){
        if(root == null){
            return;
        }
        if(root.left != null){
            parents.put(root.left, root);
            dfs(root.left);
        }
        if(root.right != null){
            parents.put(root.right, root);
            dfs(root.right);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值