LeetCode 993 Cousins in Binary Tree

栏目: 数据库 · 发布时间: 5年前

内容简介:给予一颗二叉树,和两个节点的值,判断这两个节点是否是例 :返回 true

给予一颗二叉树,和两个节点的值,判断这两个节点是否是 堂兄弟 ,即在同一层,但 父节点不同

例 :

给予树, x = 3, y = 4:

     1
   /   \
  2     3
 /
4

返回 false.


给予树, x = 5, y = 4:

     1
   /   \
  2     3
   \     \
    4     5

返回 true

解法

采用广度优先遍历, 要点是记录节点与父节点的对应关系, 然后判断是否在同一层, 这里采用队列来实现.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isCousins(TreeNode root, int x, int y) {
        if (root == null) {
            return false;
        }

        HashMap<Integer, Integer> valParentMap = new HashMap<>();

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        while(!queue.isEmpty()) {
            int size = queue.size();

            List<Integer> list = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                list.add(node.val);

                if (node.left != null) {
                    queue.add(node.left);
                    valParentMap.put(node.left.val, node.val);
                }

                if (node.right != null) {
                    queue.add(node.right);
                    valParentMap.put(node.right.val, node.val);
                }
            }

            if (list.containsAll(Arrays.asList(x, y)) && !valParentMap.get(x).equals(valParentMap.get(y))) {
                return true;
            }
        }
        return false;
    }
}
Runtime: 3 ms, faster than 68.73% of Java online submissions for Cousins in Binary Tree. Memory Usage: 34.7 MB, less than 98.52% of Java online submissions for Cousins in Binary Tree.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Computer Science Using Python

Introduction to Computer Science Using Python

Dierbach, Charles / 2012-12 / $ 133.62

Introduction to Computer Science Using Python: A Computational Problem-Solving Focus introduces students to programming and computational problem-solving via a back-to-basics, step-by-step, objects-la......一起来看看 《Introduction to Computer Science Using Python》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

MD5 加密
MD5 加密

MD5 加密工具