作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/cousins-in-binary-tree/

题目描述

In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.

Two nodes of a binary tree are cousins if they have the same depth, but have different parents.

We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.

Return true if and only if the nodes corresponding to the values x and y are cousins.

Example 1:

Input: root = [1,2,3,4], x = 4, y = 3
Output: false

Example 2:

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true

Example 3:

Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false

Note:

  1. The number of nodes in the tree will be between 2 and 100.
  2. Each node has a unique integer value from 1 to 100.

题目大意

如果一个二叉树中的两个节点的父亲不同,但是高度相同,那么这两个节点是堂兄弟。判断给出的两个值为x和y的节点是不是堂兄弟。

解题方法

DFS

如果做过987. Vertical Order Traversal of a Binary Tree,那么这个题肯定很快就能写出来。

题目要求的判断条件有两个1.父节点不同,2.高度相同,所以最直白的方法就是把每个节点的父节点和高度都求出来,然后判断x和y这两个节点是不是符合要求即可。

这个题中每个节点的值都不会重复,所以可以直接用值当做key来存储,代码很简单。

python代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
self.m = collections.defaultdict(tuple)
self.dfs(root, None, 0)
px, dx = self.m[x]
py, dy = self.m[y]
return dx == dy and px != py def dfs(self, root, parent, depth):
if not root: return
self.m[root.val] = (parent, depth)
self.dfs(root.left, root, depth + 1)
self.dfs(root.right, root, depth + 1)

C++代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
m_.clear();
dfs(root, nullptr, 0);
auto px = m_[x], py = m_[y];
return px.first != py.first && px.second == py.second;
}
private:
unordered_map<int, pair<TreeNode*, int>> m_;
void dfs(TreeNode* root, TreeNode* parent, int depth) {
if (!root) return;
m_[root->val] = make_pair(parent, depth);
dfs(root->left, root, depth + 1);
dfs(root->right, root, depth + 1);
}
};

BFS

相似的,BFS也可以做,不过更简单一点的是不用在队列里保存每个节点的高度了,因为在BFS中搜完每一层才向下一层搜索,所以可以很方便的计算每个节点的高度。

Python代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
m = collections.defaultdict(tuple)
q = collections.deque()
q.append((root, None))
depth = 0
while q:
size = len(q)
for i in range(size):
node, p = q.popleft()
if not node: continue
m[node.val] = (p, depth)
q.append((node.left, node))
q.append((node.right, node))
depth += 1
px, dx = m[x]
py, dy = m[y]
return dx == dy and px != py

C++代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
queue<pair<TreeNode*, TreeNode*>> q;
q.push(make_pair(root, nullptr));
unordered_map<int, pair<TreeNode*, int>> m_;
int depth = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; ++i) {
auto p = q.front(); q.pop();
if (!p.first) continue;
m_[p.first->val] = make_pair(p.second, depth);
q.push(make_pair(p.first->left, p.first));
q.push(make_pair(p.first->right, p.first));
}
++depth;
}
auto px = m_[x], py = m_[y];
return px.first != py.first && px.second == py.second;
}
};

日期

2019 年 2 月 21 日 —— 一放假就再难抓紧了

【LeetCode】993. Cousins in Binary Tree 解题报告(C++ & python)的更多相关文章

  1. LeetCode 993 Cousins in Binary Tree 解题报告

    题目要求 In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k ...

  2. 【LeetCode】965. Univalued Binary Tree 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https://le ...

  3. 【LeetCode】655. Print Binary Tree 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...

  4. 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)

    [LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...

  5. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

  6. 【LeetCode】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)

    [LeetCode]331. Verify Preorder Serialization of a Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...

  7. 【LeetCode】662. Maximum Width of Binary Tree 解题报告(Python)

    [LeetCode]662. Maximum Width of Binary Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.co ...

  8. LeetCode 993. Cousins in Binary Tree(判断结点是否为Cousin)

    993. Cousins in Binary Tree In a binary tree, the root node is at depth 0, and children of each dept ...

  9. 【LeetCode】236. Lowest Common Ancestor of a Binary Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

随机推荐

  1. Linux服务器I/O性能分析-2

    一.如何正确分析IO性能 1.1 BLKTRACE分析IO性能 之前的文章已经说明,要是系统发生I/O性能问题,我们常用的命令是无法精确定位问题(内核I/O调度器消耗的时间和硬件消耗的时间,这个不能作 ...

  2. 『学了就忘』Linux文件系统管理 — 64、磁盘配额的配置步骤

    目录 1.手工建立一个5GB的分区 2.建立需要做限制的三个用户 3.在分区上开启磁盘配额功能 4.建立磁盘配额的配置文件 5.开始设置用户和组的配额限制 6.启动和关闭配额 7.磁盘配额的查询 8. ...

  3. 学习java的第二十三天

    一.今日收获 1.java完全学习手册第三章算法的3.2排序,比较了跟c语言排序上的不同 2.观看哔哩哔哩上的教学视频 二.今日问题 1.快速排序法的运行调试多次 2.哔哩哔哩教学视频的一些术语不太理 ...

  4. 启动spark-shell --master yarn的bug

    报错如下 18/06/06 15:55:31 ERROR cluster.YarnClientSchedulerBackend: Yarn application has already exited ...

  5. C++字节对齐(对象大小)

    内部数据成员对齐参考这篇 https://www.cnblogs.com/area-h-p/p/10316128.html 这里只强调C++字节对齐特点 ①静态数据成员属于类域,在对象中不占大小 ②若 ...

  6. Oracle数据库导入与导出方法简述

    说明: 1.数据库数据导入导出方法有多种,可以通过exp/imp命令导入导出,也可以用第三方工具导出,如:PLSQL 2.如果熟悉命令,建议用exp/imp命令导入导出,避免第三方工具版本差异引起的问 ...

  7. Oracle中的null与空字符串''的区别

    含义解释:问:什么是NULL?答:在我们不知道具体有什么数据的时候,也即未知,可以用NULL,我们称它为空,ORACLE中,含有空值的表列长度为零.ORACLE允许任何一种数据类型的字段为空,除了以下 ...

  8. mysql 5.7 压缩包安装教程

    前言 :  避免之前装的MySQL影响 首先进入dos窗口执行 sc delete mysql      删除已有的mysql服务 (一) 下载MySQL5.7 版本压缩包 网址 https://de ...

  9. 使用MySQL的SELECT INTO OUTFILE ,Load data file,Mysql 大量数据快速导入导出

    使用MySQL的SELECT INTO OUTFILE .Load data file LOAD DATA INFILE语句从一个文本文件中以很高的速度读入一个表中.当用户一前一后地使用SELECT ...

  10. 【Service】【Database】【Cache】Redis

    1. 简介: 1.1. redis == REmote DIctionary Server 1.2. KV cache and store, in-memory, 持久化,主从(sentinel实现一 ...