In a binary tree, the root node is at depth 0
, and children of each depth k
node are at depth k+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 values x
and y
of two different nodes in the tree.
Return true
if and only if the nodes corresponding to the values x
and y
are cousins.
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
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
。否则,返回 false
。
示例 1:
输入:root = [1,2,3,4], x = 4, y = 3 输出:false
示例 2:
输入:root = [1,2,3,null,4,null,5], x = 5, y = 4 输出:true
示例 3:
输入:root = [1,2,3,null,4], x = 2, y = 3 输出:false
提示:
- 二叉树的节点数介于
2
到100
之间。 - 每个节点的值都是唯一的、范围为
1
到100
的整数。
Runtime: 12 ms
Memory Usage: 18.4 MB
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 var ddd:Int = 0 16 func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool { 17 var px:TreeNode? = dfs(root, nil, x, 0, 1) 18 var py:TreeNode? = dfs(root, nil, y, 0, -1) 19 return x != y && px != nil && py != nil && px!.val != py!.val && ddd == 0 20 } 21 22 func dfs(_ cur:TreeNode?,_ par:TreeNode?,_ x:Int,_ dep:Int,_ mul:Int) -> TreeNode? 23 { 24 if cur == nil {return nil} 25 if cur!.val == x 26 { 27 ddd += dep * mul 28 return par 29 } 30 var res:TreeNode? = dfs(cur!.left, cur, x, dep + 1, mul) 31 if res != nil {return res} 32 res = dfs(cur!.right, cur, x, dep+1, mul) 33 return res 34 } 35 }
原文地址:https://www.cnblogs.com/strengthen/p/10390643.html
时间: 2024-09-30 20:40:11