这道题比较经典,并且有两种BFS和DFS两种解法,所以写一篇博客总结一下。代码里有注释,方便大家理解~
- Breadth-First Search
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isCousins(TreeNode root, int x, int y) { Queue<TreeNode> q = new LinkedList<>(); q.offer(root); //isEmpty() is a method inherited from interface java.util.Collection while(!q.isEmpty()){ // Be cautious that we have to store the size of queue in advance // because q.size() will keep changing int size = q.size(); boolean xExist = false; boolean yExist = false; // For loop controls the BFS breadth for(int i = 0; i < size; i++){ TreeNode cur = q.poll(); if(cur.val == x){ xExist = true; }else if(cur.val == y){ yExist = true; } if(cur.left != null && cur.right != null){ if(cur.left.val == x && cur.right.val == y){ return false; }else if(cur.left.val == y && cur.right.val == x){ return false; } } if(cur.left != null){ q.offer(cur.left); } if(cur.right != null){ q.offer(cur.right); } } if(xExist && yExist){ return true; }else if(xExist || yExist){ // If we only find one node in this level, we can conclude that they are not cousins. return false; } } return false; } }
- Depth-First Search
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { // Initialization int xDepth = -1, yDepth = -1; TreeNode xParent, yParent; // We need to keep track of the depth and parent node, so we put them into the parameters of the dfs function. // Traverse the whole tree and find the nodes whose values are x and y respectively. private void dfs(TreeNode node, int x, int y, int depth, TreeNode parent){ // base case if(node == null){ return; } if(node.val == x){ xDepth = depth; xParent = parent; }else if(node.val == y){ yDepth = depth; yParent = parent; }else{ // If we have found x or y, then we do not have to go further because cousins must have the same // depth. dfs(node.left, x, y, depth + 1, node); dfs(node.right, x, y, depth + 1, node); } } public boolean isCousins(TreeNode root, int x, int y) { dfs(root, x, y, 0, new TreeNode(0)); return xDepth == yDepth && xParent != yParent; } }