Leetcode 993:二叉树的堂兄弟结点

题目描述

在二叉树中,根节点位于深度0处,每个深度为k的结点的子节点位于k+1处。如果二叉树的两个结点深度相同,但父节点不同,则他们是一对堂兄弟结点。我们给出了具体唯一值的二叉树的根节点root,以及树中两个不同祭祀按的值x和y。只有与x和y对应的结点是堂兄弟结点时,才返回true。否则,f返回false

示例1

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

输出:false

示例2

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

输出:true

示例3

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

输出:fasle

解题思路

DFS:深度遍历二叉树,记录每一层结点的深度和由根节点到叶子结点的路径,如果找到x,记录x的深度及其父节点,如果找到y记录y的深度和父节点。然后依次判断父节点是否相等,深度是否相等。

class Solution {
public:
    vector<int> depths;
    vector<int> fathers;
    vector<int> vect;
    void depth(TreeNode* root,int dep,int x,int y){
        if(root == NULL) return;
        if(root->val == x || root->val == y){
            depths.push_back(dep);
            if(vect.size() >= 1) fathers.push_back(vect[vect.size()-1]);
            else fathers.push_back(0);
        }
        vect.push_back(root->val);
        depth(root->left,dep + 1,x,y);
        depth(root->right,dep + 1,x,y);
        vect.pop_back();
    }
    bool isCousins(TreeNode* root, int x, int y) {
        depth(root,0,x,y);
        if(fathers[0] == fathers[1]) return false;
        if(depths[0] != depths[1]) return false;
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_35338624/article/details/87910116