一、题目

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

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

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

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

点击查看原题

二、思路

根据题意,只需要找到x和y节点的深度和父节点,进行比较判断即可。
遍历二叉树的方式有深度遍历和广度遍历,我们只选用一种作为编程演示即可,本题较为简单,可自行实现另一种方法。两个问题:
1、如何记录父节点?
直接拿着当前节点去判断节点的左右孩子节点是否为x或y,如果是,这样当前节点就是父节点,直接记录。
2、如何记录深度?
使用一个变量depth,在迭代的时候,每迭代一次,传参+1即可。

三、代码

  1. class Solution {
  2. private TreeNode xF = null, yF = null;
  3. private int xDepth = 0, yDepth = 0;
  4. public boolean isCousins(TreeNode root, int x, int y) {
  5. dfs(root, x, y, 1);
  6. if (xDepth == yDepth) {
  7. return (xF != null) && (yF != null) && (xF != yF);
  8. }
  9. return false;
  10. }
  11. private void dfs(TreeNode root, int x, int y, int depth) {
  12. if (root == null) {
  13. return ;
  14. }
  15. if (root.left != null) {
  16. if (root.left.val == x) {
  17. xDepth = depth;
  18. xF = root;
  19. return;
  20. }
  21. if (root.left.val == y) {
  22. yDepth = depth;
  23. yF = root;
  24. return;
  25. }
  26. }
  27. if (root.right != null) {
  28. if (root.right.val == x) {
  29. xDepth = depth;
  30. xF = root;
  31. return;
  32. }
  33. if (root.right.val == y) {
  34. yDepth = depth;
  35. yF = root;
  36. return;
  37. }
  38. }
  39. dfs(root.left, x, y, depth+1);
  40. dfs(root.right, x, y, depth+1);
  41. }
  42. }

时间复杂度为O(n),空间复杂度为O(h),h为树的高度。