993. Cousins in Binary Tree

问题:

求给定二叉树中,x节点和y节点是否为表兄弟关系。

表兄弟关系为:在同一层&&父节点不同。

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
 
Constraints:
The number of nodes in the tree will be between 2 and 100.
Each node has a unique integer value from 1 to 100.

  

example 1:

example 2:

example 3:

解法:BFS

状态:

  • 当前node
  • 当前node的父节点id

对于每一层遍历中,需要:

  • 同时找到 x和 y,且其父节点不同,那么返回true。
  • 父节点相同,返回false。
  • 该层遍历完毕,只找到x or y,返回false。
  • 最终遍历完树,还未找到,返回false。

代码参考:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     bool isCousins(TreeNode* root, int x, int y) {
15         queue<pair<TreeNode*,int>> q;//node,parent
16         if(root) q.push({root,-1});
17         int x_p=-1, y_p=-1;
18         while(!q.empty()) {
19             int sz = q.size();
20             for(int i=0; i<sz; i++) {
21                 auto [node, parent] = q.front();
22                 q.pop();
23                 if(node->val == x) x_p = parent;
24                 else if(node->val == y) y_p = parent;
25                 if(x_p!=-1 && y_p!=-1 && x_p!=y_p) return true;
26                 else if(x_p!=-1 && y_p!=-1 && x_p==y_p) return false;
27                 if(node->left) q.push({node->left, node->val});
28                 if(node->right) q.push({node->right, node->val});
29             }
30             if((x_p!=-1 && y_p==-1) || (x_p==-1 && y_p!=-1)) return false;
31         }
32         return false;
33     }
34 };
35 点击并拖拽以移动
原文地址:https://www.cnblogs.com/habibah-chang/p/14562597.html