每日一题:993.二叉树的堂兄弟节点
题目
解题思路
遍历一遍就好
/**
* 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) {
int[][] arr = new int[2][2];
arr[0][1] = -1;
arr[1][1] = -1;
dfs(root, 0, x, y, 0, arr);
// System.out.println(arr[0][1]);
// System.out.println(arr[1][1]);
if(arr[0][1] == arr[1][1] && arr[0][0] != arr[1][0]) return true;
return false;
}
private void dfs(TreeNode root, int pre, int x, int y, int high, int[][] arr) {
// TODO Auto-generated method stub
if(arr[0][1] != -1 && arr[1][1] != -1) return;
if(root == null) {
return ;
}
if (root.val == x ) {
arr[0][0] = pre;
arr[0][1] = high;
return ;
}
if (root.val == y ) {
arr[1][0] = pre;
arr[1][1] = high;
return ;
}
dfs(root.left, root.val, x, y, high+1, arr);
dfs(root.right, root.val, x, y, high+1, arr);
return ;
}
}