In a binary tree, the root node is at depth
0
, and children of each depthk
node are at depthk+1
.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the
root
of a binary tree with unique values, and the valuesx
andy
of two different nodes in the tree.
Return
true
if and only if the nodes corresponding to the valuesx
andy
are cousins.
Note:
- The number of nodes in the tree will be between
2
and100
.- Each node has a unique integer value from
1
to100
.
在一個二元樹中,樹根節點的深度是
0
,每個深度為k
的節點,他們的小孩深度為k+1
。
二元樹中兩個節點如果是表親,則它們擁有一樣的深度但父親不同。
我們給予二元樹中的
root
且所有節點都有不同的值,還有兩個不同節點中的值x
和y
。
如果
x
和y
對應的節點是表親的話,回傳true
。
提示:
- 樹擁有的節點數量介於
2
到100
。- 節點中不重複的值介於
1
到100
。
BFS
去跑,而結果就會按照樹的深度去跑,這剛好就是我們要的。BFS
,跑到x
或y
時去紀錄深度和父親即可。
BFS
的queue
結構可以使用STL就好。LeetCode
C++