993. Cousins in Binary Tree

题目描述

在这里插入图片描述在这里插入图片描述在这里插入图片描述

方法思路

基本思路就是使用深度优先搜索

Approach1: based on Maps

class Solution {
    //Runtime: 4 ms, faster than 79.97%
    //Memory Usage: 37.2 MB, less than 45.22%
    Map<Integer, Integer> depth;
    Map<Integer, TreeNode> parent;

    public boolean isCousins(TreeNode root, int x, int y) {
        depth = new HashMap();
        parent = new HashMap();
        dfs(root, null);
        return (depth.get(x) == depth.get(y) && parent.get(x) != parent.get(y));
    }

    public void dfs(TreeNode node, TreeNode par) {
        if (node != null) {
            depth.put(node.val, par != null ? 1 + depth.get(par.val) : 0);
            parent.put(node.val, par);
            dfs(node.left, node);
            dfs(node.right, node);
        }
    }
}

Approach2: based on arr

class Solution {
    //Runtime: 6 ms, faster than 11.41%
    //Memory Usage: 37.6 MB, less than 5.18%
    int[] arr;
    public boolean isCousins(TreeNode root, int x, int y) {
        if(root == null) 
            return false;
        if(root.val == x || root.val == y)
            return false;
        int[] x_Info = find_Info(root, x, 0);
        int[] y_Info = find_Info(root, y, 0);
        if(x_Info[0] == y_Info[0] && x_Info[1] != y_Info[1])
            return true;
        return false;
    }
    public int[] find_Info(TreeNode root, int val, int depth){
        if(root != null){
            if(root.left != null ){
                if(root.left.val == val){
                    arr = new int[2];
                    arr[0] = depth + 1;
                    arr[1] = root.val;
                    return arr;
                }else{
                    find_Info(root.left, val, depth + 1);
                    find_Info(root.right, val, depth + 1);
                }
            }
            if(root.right != null ){
                if(root.right.val == val){
                    arr = new int[2];
                    arr[0] = depth + 1;
                    arr[1] = root.val;
                    return arr;
                }else{
                    find_Info(root.left, val, depth + 1);
                    find_Info(root.right, val, depth + 1);
                }
            }
        }
        return arr;
    }
}

猜你喜欢

转载自blog.csdn.net/IPOC_BUPT/article/details/88619137
今日推荐