项目作者: eMahtab

项目描述 :
Check whether given two nodes are cousins in a binary tree
高级语言:
项目地址: git://github.com/eMahtab/cousins-in-binary-tree.git
创建时间: 2020-02-02T05:47:39Z
项目社区:https://github.com/eMahtab/cousins-in-binary-tree

开源协议:

下载


Cousins in Binary Tree

https://leetcode.com/problems/cousins-in-binary-tree

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.

Implementation :

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. Map<Integer,Integer> parentMap = new HashMap<>();
  18. Map<Integer,Integer> depthMap = new HashMap<>();
  19. public boolean isCousins(TreeNode root, int x, int y) {
  20. if(root == null)
  21. return false;
  22. dfs(root, null, 0);
  23. return (parentMap.get(x) != parentMap.get(y)) && (depthMap.get(x) == depthMap.get(y));
  24. }
  25. private void dfs(TreeNode node, TreeNode parent, int depth) {
  26. parentMap.put(node.val, parent == null ? null : parent.val);
  27. depthMap.put(node.val, depth);
  28. if(node.left != null)
  29. dfs(node.left, node, depth+1);
  30. if(node.right != null)
  31. dfs(node.right, node, depth+1);
  32. }
  33. }

Implementation 2:

  1. class Solution {
  2. public boolean isCousins(TreeNode root, int x, int y) {
  3. if(root == null)
  4. return false;
  5. Map<Integer, Integer> depthMap = new HashMap<>();
  6. Map<Integer, Integer> parentMap = new HashMap<>();
  7. depthMap.put(root.val, 0); parentMap.put(root.val, Integer.MIN_VALUE);
  8. traverseTree(root, depthMap, parentMap, 0);
  9. return depthMap.get(x) == depthMap.get(y) && parentMap.get(x) != parentMap.get(y);
  10. }
  11. private void traverseTree(TreeNode node, Map<Integer, Integer> depthMap,
  12. Map<Integer, Integer> parentMap, int depth) {
  13. if(node.left != null) {
  14. depthMap.put(node.left.val, depth+1);
  15. parentMap.put(node.left.val, node.val);
  16. traverseTree(node.left, depthMap, parentMap, depth+1);
  17. }
  18. if(node.right != null) {
  19. depthMap.put(node.right.val, depth+1);
  20. parentMap.put(node.right.val, node.val);
  21. traverseTree(node.right, depthMap, parentMap, depth+1);
  22. }
  23. }
  24. }