993.二叉树的堂兄弟节点

题目描述:

image.png


解:

因为需要知道父节点和深度,所以需要用dfs或bfs的方式去遍历,选择dfs的原因是比bfs更好写…

  1. class Solution {
  2. int x; //记录x
  3. int xDepth;
  4. TreeNode xParent;
  5. boolean xFound = false;
  6. int y; //记录y
  7. int yDepth;
  8. TreeNode yParent;
  9. boolean yFound = false;
  10. private void dfs(TreeNode root,int depth,TreeNode parent) {
  11. if(root == null) {
  12. return;
  13. }
  14. if(xFound && yFound) { //都找到了就可以返回了
  15. return;
  16. }
  17. if(root.val == x) {
  18. xDepth = depth;
  19. xParent = parent;
  20. xFound = true;
  21. } else if(root.val == y) {
  22. yDepth = depth;
  23. yParent = parent;
  24. yFound = true;
  25. }
  26. if(xFound && yFound) {
  27. return;
  28. }
  29. dfs(root.left,depth+1,root);
  30. dfs(root.right, depth + 1, root);
  31. }
  32. public boolean isCousins(TreeNode root, int x, int y) {
  33. this.x = x;
  34. this.y = y;
  35. dfs(root,0,null);
  36. return xDepth == yDepth && xParent != yParent;
  37. }
  38. }