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

时间:2023-03-09 06:32:46
Leetcode 993. 二叉树的堂兄弟节点

993. 二叉树的堂兄弟节点

 显示英文描述
  • 用户通过次数195
  • 用户尝试次数229
  • 通过次数195
  • 提交次数462
  • 题目难度Easy

在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。

如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点

我们给出了具有唯一值的二叉树的根节点 root,以及树中两个不同节点的值 x 和 y

只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true。否则,返回 false

示例 1:
Leetcode 993. 二叉树的堂兄弟节点

输入:root = [1,2,3,4], x = 4, y = 3
输出:false

示例 2:
Leetcode 993. 二叉树的堂兄弟节点

输入:root = [1,2,3,null,4,null,5], x = 5, y = 4
输出:true

示例 3:

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

输入:root = [1,2,3,null,4], x = 2, y = 3
输出:false

提示:

  1. 二叉树的节点数介于 2 到 100 之间。
  2. 每个节点的值都是唯一的、范围为 1 到 100 的整数。
/**
* 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:
map<int,int> mp; void createparent(TreeNode* root){
if(root->left){mp[root->left->val] = root->val; createparent(root->left);}
if(root->right){mp[root->right->val] = root->val; createparent(root->right);}
return;
} int treelen(TreeNode* root,int cnt,int x){
if(!root) return -;
if(root->val == x)return cnt;
return max(treelen(root->left,cnt+,x),treelen(root->right,cnt+,x));
} bool isCousins(TreeNode* root, int x, int y) {
createparent(root);
int a = treelen(root,,x);
int b = treelen(root,,y);
// cout << a << " " << b;
// cout << mp[x] << " " << mp[y];
if(a == b&&mp[x]!=mp[y])return true;
return false;
}
};

下手之前先理清思路,一开始写了个层序遍历才发现不对。。