码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-993 Cousins in Binary Tree(二叉树的堂兄弟节点)

时间:2019-02-17 12:54:14      阅读:420      评论:0      收藏:0      [点我收藏+]

标签:pre   val   amp   false   public   color   ret   etc   div   

 1 class Solution
 2 {
 3     public:
 4         bool judge(TreeNode* root, int x, int y)
 5         {
 6             if(root!=NULL)
 7             {
 8 
 9                 if(root->left&&root->right)
10                     if((root->left->val==x&&root->right->val==y)
11                     ||(root->left->val==y&&root->right->val==x))
12                     {
13                         return false;
14                     }
15                 if(!judge(root->left,x,y))
16                     return false;
17                 if(!judge(root->right,x,y))
18                     return false;
19             }
20             return true;
21         }
22         bool isCousins(TreeNode* root, int x, int y)
23         {
24             if(!judge(root,x,y))
25                 return false;
26             queue<pair<TreeNode*,int>> q;
27             q.push({root,0});
28             int rnt1,rnt2;
29             while(!q.empty())
30             {
31                 pair<TreeNode*,int> t = q.front();
32                 q.pop();
33                 if(t.first->val==x)
34                 {
35                     rnt1 = t.second;
36                 }
37                 else if(t.first->val==y)
38                 {
39                     rnt2 = t.second;
40                 }
41                 if(t.first->left)
42                     q.push({t.first->left,t.second+1});
43                 if(t.first->right)
44                     q.push({t.first->right,t.second+1});
45             }
46             if(rnt1==rnt2)
47             {
48                 return true;
49             }
50             return false;
51         }
52 };

 

Leetcode-993 Cousins in Binary Tree(二叉树的堂兄弟节点)

标签:pre   val   amp   false   public   color   ret   etc   div   

原文地址:https://www.cnblogs.com/Asurudo/p/10390638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!