牛客网:NC102 在二叉树中找到两个节点的最近公共祖先

递归写法:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    // 递归解法, 
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        // write code here
        return help(root, o1, o2).val;
    }
    
    private TreeNode help(TreeNode root, int x, int y){
        if (root == null || root.val == x || root.val == y){
            return root;
        }
        TreeNode left = help(root.left, x, y);
        TreeNode right = help(root.right, x, y);
        if (left == null){
            return right;
        }
        if (right == null){
            return left;
        }
        return root;
    }
}

迭代写法:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    // 记录路径
    public int lowestCommonAncestor (TreeNode root, int m, int n) {
        // write code here
        Map<Integer ,Integer> map = new HashMap<>();
        Queue<TreeNode> deque = new LinkedList<>();
        map.put(root.val, Integer.MAX_VALUE);
        deque.add(root);
        while (!map.containsKey(m) || !map.containsKey(n)){
            TreeNode temp = deque.poll();
            if (temp.left != null){
                deque.add(temp.left);
                map.put(temp.left.val, temp.val);
            }
            if (temp.right != null){
                deque.add(temp.right);
                map.put(temp.right.val, temp.val);
            }
        }
        Set<Integer> set = new HashSet<>();
        // 找到节点1的所有父节点
        while (map.containsKey(m)){
            set.add(m);
            m = map.get(m);
        }
        
        while(!set.contains(n)){
            n = map.get(n);
        }
        return n;
        
     }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值