• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

Recommended Posts

993. 二叉树的堂兄弟节点

在二叉树中,根节点位于深度0处,每个深度为k的节点的子节点位于深度k 1处。

如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。

我们给出了具有唯一值的二叉树的根节点根,以及树中两个不同节点的值x和y。

只有与值x和y对应的节点是堂兄弟节点时,才返回没错。否则,返回错误。

示例1:

q1248-01.png

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

输出:错误

示例2:

q1248-02.png

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

输出:正确

示例3:

q1248-03.png

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

输出:错误

提示:

二叉树的节点数介于2到100之间。

每个节点的值都是唯一的、范围为一到100的整数。

1 /**

2 *二叉树节点的定义。

3 *结构树节点{

4 *整型值

5 * TreeNode *左

6 * TreeNode *右

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(左),对吧(右){}

10 * };

11 */

12级解决方案{

13 public:

14 unordered_mapint,std:pairint,TreeNode * hashMap//键-节点值,值-(深度,父节点)

15 bool is cosins(TreeNode * root,int x,int y) {

16 if (root==nullptr) {

17返回假;

18 }

19 queueTreeNode * q;

20问推(根);

21 hashMap[根值].first=0;

22 hashMap[根值].秒=根;

23 int step=0;

24 while(!q.empty()) {

25 int size=q . size();

26步;

27 for(int I=0;我尺寸;i ) {

28 TreeNode * curNode=q . front();

29 q . pop();

30 if (curNode==nullptr) {

31继续;

32 }

33 if (curNode-left!=nullptr) {

34 q . push(curNode-左);

35 hashMap[curNode-left-val].第一=步;

36 hashMap[curNode-left-val].秒=curNode

37 }

38 if(curNode-右!=nullptr) {

39 q . push(curNode-right);

40 hashMap[curNode-right-val].第一=步;

41 hashMap[curNode-right-val].秒=curNode

42 }

43 }

44 }

45 auto xInfo=hashmap。find(x);

46汽车佛印=hashmap。查找(y);

47 //x或者y的深度和父节点不存在,则返回错误的

48 if (xInfo==hashMap.end() ||佛印==hashMap.end()) {

49返回假;

50 }

51 //只有x和y的深度、父节点均存在,且x和y深度相同,x和y的父节点不同时才返回真实的

52 if (xInfo-second.first==佛印-第二,第一

53新佛-秒秒!=佛印-秒。秒){

54返回真实的

55 }

56返回假;

57 }

58 };

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now