[LeetCode]993. 二叉树的堂兄弟节点(Java/c++ DFS)
Posted 醉苼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]993. 二叉树的堂兄弟节点(Java/c++ DFS)相关的知识,希望对你有一定的参考价值。
Java/c++ DFS
解题思路
遍历树,找到x和y的深度和父节点即可
代码:
Java:
/**
* 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 {
private int x_depth = 0;
private int y_depth = 0;
private TreeNode x_father = null;
private TreeNode y_father = null;
public boolean isCousins(TreeNode root, int x, int y) {
dfs(root,x,y,0);
return x_depth == y_depth && x_father != y_father;
}
public void dfs(TreeNode root, int x, int y, int depth) {
if(root == null) return ;
if(root.left != null) {
if(root.left.val == x) {
x_depth = depth+1;
x_father = root;
}
if(root.left.val == y) {
y_depth = depth+1;
y_father = root;
}
dfs(root.left,x,y,depth+1);
}
if(root.right != null) {
if(root.right.val == x) {
x_depth = depth+1;
x_father = root;
}
if(root.right.val == y) {
y_depth = depth+1;
y_father = root;
}
dfs(root.right,x,y,depth+1);
}
}
}
c++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int x_depth = 0;
int y_depth = 0;
TreeNode* x_father;
TreeNode* y_father;
public:
bool isCousins(TreeNode* root, int x, int y) {
dfs(root,x,y,0);
return x_depth == y_depth && x_father != y_father;
}
void dfs(TreeNode* root, int x, int y, int depth) {
if(root == nullptr) return ;
if(root->left != nullptr) {
if(root->left->val == x) {
x_depth = depth+1;
x_father = root;
}
if(root->left->val == y) {
y_depth = depth+1;
y_father = root;
}
dfs(root->left,x,y,depth+1);
}
if(root->right != nullptr) {
if(root->right->val == x) {
x_depth = depth+1;
x_father = root;
}
if(root->right->val == y) {
y_depth = depth+1;
y_father = root;
}
dfs(root->right,x,y,depth+1);
}
}
};
以上是关于[LeetCode]993. 二叉树的堂兄弟节点(Java/c++ DFS)的主要内容,如果未能解决你的问题,请参考以下文章
⭐算法入门⭐《二叉树》简单07 —— LeetCode 993. 二叉树的堂兄弟节点
追求最优美的代码 leetcode 993. 二叉树的堂兄弟节点
追求最优美的代码 leetcode 993. 二叉树的堂兄弟节点