993. 二叉树的堂兄弟节点

Posted Debroon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了993. 二叉树的堂兄弟节点相关的知识,希望对你有一定的参考价值。

993. 二叉树的堂兄弟节点

 


题目

传送门:https://leetcode.cn/problems/cousins-in-binary-tree/


 


算法设计:深度优先搜索

遍历找到 x,y 的深度和父节点,对比即可。

class Solution 
public:
    bool isCousins(TreeNode* root, int x, int y) 
		unordered_map<int, pair<int, int>> m;
		dfs(root, 0, -1, m);
		return m[x].first == m[y].first && m[x].second != m[y].second;
		// 判断 x,y 是否是表兄弟节点
    
    void dfs(TreeNode* root, int depth, int parent, unordered_map<int, pair<int, int>>& m) 
    	if (!root) return;
    	m[root->val] = depth, parent;            // 记录深度和父节点
    	dfs(root->left, depth + 1, root->val, m);
    	dfs(root->right, depth + 1, root->val, m);
    
;

以上是关于993. 二叉树的堂兄弟节点的主要内容,如果未能解决你的问题,请参考以下文章

⭐算法入门⭐《二叉树》简单07 —— LeetCode 993. 二叉树的堂兄弟节点

力扣每日一题:993. 二叉树的堂兄弟节点(简单)

LeetCode 993 二叉树的堂兄弟节点[DFS 回溯] HERODING的LeetCode之路

993. 二叉树的堂兄弟节点

leetcode 993. 二叉树的堂兄弟节点

leetcode993. 二叉树的堂兄弟节点