【leetcode每日刷题】236. Lowest Common Ancestor of a Binary Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

1、创建stack,和map,stack用于遍历路径,map用于保存遍历的每个节点的父节点,直到p和q的父节点都已经遍历到。

2、创建ancestor set,存储p节点含自己的所有父节点

3、回溯q节点的所有父节点,直到它是可以在set中找到的。如果没有找到,返回根节点的父节点null。

package leetcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class num236 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        Stack stack = new Stack<>();
        Map map = new HashMap<>();
        stack.push(root);
        map.put(root, null);
        while(!map.containsKey(p) || !map.containsKey(q)){
            root = stack.pop();
            if(root.left != null){
                stack.push(root.left);
                map.put(root.left, root);
            }
            if(root.right != null){
                stack.push(root.right);
                map.put(root.right, root);
            }
        }
        Set ancestor = new HashSet<>();
        while(p!=null){
            ancestor.add(p);
            p = map.get(p);
        }
        while(!ancestor.contains(q)){
            q = map.get(q);
        }
        return q;
    }
}

 

你可能感兴趣的:(java,leetcode刷题)