【LeetCode】993. Cousins in Binary Tree 解题报告(C++ & python)
作者: 负雪明烛
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:
- The number of nodes in the tree will be between 2 and 100.
- 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)的更多相关文章
- 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 ...
- 【LeetCode】965. Univalued Binary Tree 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https://le ...
- 【LeetCode】655. Print Binary Tree 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...
- 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)
[LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...
- 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)
[LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...
- 【LeetCode】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)
[LeetCode]331. Verify Preorder Serialization of a Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...
- 【LeetCode】662. Maximum Width of Binary Tree 解题报告(Python)
[LeetCode]662. Maximum Width of Binary Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.co ...
- 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 ...
- 【LeetCode】236. Lowest Common Ancestor of a Binary Tree 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
随机推荐
- 【机器学习与R语言】10- 关联规则
目录 1.理解关联规则 1)基本认识 2)Apriori算法 2.关联规则应用示例 1)收集数据 2)探索和准备数据 3)训练模型 4)评估性能 5)提高模型性能 1.理解关联规则 1)基本认识 购物 ...
- 在windows下使用shell,运行shell脚本
在Windows操作系统下运行Shell脚本,缺少的只是一个Git软件.其下载路径为Git - Downloading Package. 安装之后,将安装路径下的bin文件夹的路径作为环境变量.于是我 ...
- chown & chmod用法
chown & chmod 1. chown更改文件的属主&属组 NAME chown - 改变文件的属主和属组(change file owner and group) 用法 cho ...
- Redis | 第10章 二进制数组、慢查询日志和监视器《Redis设计与实现》
目录 前言 1. 二进制位数组 1.1 位数组的表示 1.2 GETBIT 命令的实现 1.3 SETBIT 命令的实现 1.4 BITECOUNT 命令的实现 1.5 BITOP 命令的实现 2. ...
- accommodate, accompany
accommodate 词源: to make fit, suitable; 近/反义词: adapt, adjust, lodge; disoblige, incommode, misfit Lod ...
- pyqt5 的串口编写进度
2020.12.18 今天遇到一个问题, 想用回车实现串口数据的发送. 下面这句话是让光标移动到文字的尾部,但是不能够实现. 对QTextEdit控件中的文字改写,或清除后,再调用下面的移动到尾部,就 ...
- Tomcat中的Server.xml配置详解
Tomcat中的Server.xml配置详解 Tomcat Server的结构图如下: 该文件描述了如何启动Tomcat Server <Server> <Listener /> ...
- Https原理及证书管理
Https原理及证书管理 SSL(Secure Sockets Layer,安全套接层)/TLS(Transport Layer Security,传输层安全)保证了客户端web服务器的连接安全.客户 ...
- Oracle之DBMS_LOCK包用法详解
概述与背景 某些并发程序,在高并发的情况下,必须控制好并发请求的运行时间和次序,来保证处理数据的正确性和完整性.对于并发请求的并发控制,EBS系统可以通过Concurrent Program定义界面的 ...
- java生成cron表达式
bean类: package com.cst.klocwork.service.cron; public class TaskScheduleModel { /** * 所选作业类型: * 1 -&g ...