作者: 负雪明烛
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. 【宏基因组】MEGAN4,MEGAN5和MEGAN6的Linux安装和使用

    MEGAN(Metagenome Analyzer)是宏基因组学进行物种和功能研究的常用软件,实际上现在的Diamond+MEGAN6已经是一套比较完整的物种和功能注释流程了. 但是由于各种原因,我们 ...

  2. shell批量创建用户

    #!/bin/bash cat << EOF ************************************************************ 批量添加用户并随机生 ...

  3. 学习java 7.8

    学习内容: 被static修饰的不需要创建对象,直接用类名引用即可 内部类访问特点:内部类可以直接访问外部类的成员,包括私有 外部类访问内部类的成员,必须创建对象 成员内部类,内部类为私有,Outer ...

  4. 位运算符在JS中的妙用

    正文 位运算 JavaScript 中最臭名昭著的 Bug 就是 0.1 + 0.2 !== 0.3,因为精度的问题,导致所有的浮点运算都是不安全的,具体原因可详见<0.1 + 0.2不等于0. ...

  5. Angular中@Output()的使用方法

    子component中的html文件 <button (click)="Send()">送出</button><br> 子component中的 ...

  6. Advanced C++ | Conversion Operators

    In C++, the programmer abstracts real world objects using classes as concrete types. Sometimes it is ...

  7. OC中的结构体

    一.结构体 结构体只能在定义的时候进行初始化 给结构体属性赋值    + 强制转换: 系统并不清楚是数组还是结构体,需要在值前面加上(结构体名称)    +定义一个新的结构体,进行直接赋值    + ...

  8. CountDownLatch原理

    正如每个Java文档所描述的那样,CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行.在Java并发中,countdownlatch的概念是一 ...

  9. JavaScript实现数组去重方法

    一.利用ES6 Set去重(ES6中最常用) function unique (arr) { return Array.from(new Set(arr)) } var arr = [1,1,'tru ...

  10. 【HarmonyOS】【DevEco Studio】NOTE04:How to Jump to a Page(页面间的跳转)

    页面创建与基本设置 创建页面 创建两个新页面,分别为AbilityPage1.AbilityPage2 设置页面基本内容 以AbilityPage1为例 导包 import com.example.m ...