LeetCode 993. 二叉树的堂兄弟节点(前序遍历判断是否一个父亲+层次遍历判断是否在同一层)
程序员文章站
2022-05-20 20:23:54
...
二叉树的堂兄弟节点代码有些冗余
两次遍历都是
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
if(preOrder(root,x,y)){
return false;
}
return layerOrder(root,x,y);
}
bool layerOrder(TreeNode *root,int x,int y){
queue<TreeNode*> q;
q.push(root);
int l;
while(!q.empty()){
int size = q.size();
set<int> res;
while(size--){
TreeNode* r = q.front();
q.pop();
res.insert(r->val);
if(r->left){
q.push(r->left);
}
if(r->right){
q.push(r->right);
}
}
if(res.count(x) && res.count(y) ){
return true;
}
}
return false;
}
bool preOrder(TreeNode *root,int x,int y){
if(!root || (!root->left && !root->right)){
return false;
}
if(root->left && root->right){
if( (root->left->val==x && root->right->val==y) ||
( (root->left->val==y && root->right->val==x)) ){
return true;
}
}
if(root->left && preOrder(root->left,x,y) ){
return true;
}
if(root->right && preOrder(root->right,x,y) ){
return true;
}
return false;
}
};