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。

 

代码参考:

/**
 * 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) {
        queue<pair<TreeNode*,int>> q;//node,parent
        if(root) q.push({root,-1});
        int x_p=-1, y_p=-1;
        while(!q.empty()) {
            int sz = q.size();
            for(int i=0; i<sz; i++) {
                auto [node, parent] = q.front();
                q.pop();
                if(node->val == x) x_p = parent;
                else if(node->val == y) y_p = parent;
                if(x_p!=-1 && y_p!=-1 && x_p!=y_p) return true;
                else if(x_p!=-1 && y_p!=-1 && x_p==y_p) return false;
                if(node->left) q.push({node->left, node->val});
                if(node->right) q.push({node->right, node->val});
            }
            if((x_p!=-1 && y_p==-1) || (x_p==-1 && y_p!=-1)) return false;
        }
        return false;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值