Я пытаюсь решить задачу LeetCode 1448. Подсчитайте хорошие узлы в двоичном дереве:
При наличии корня двоичного дерева узел < em>X в дереве называется good, если на пути от корня до X нет узлов со значением больше > X.
Вернуть количество хороших узлов в бинарном дереве.
Это было мое решение:
Код: Выделить всё
/**
* 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 int goodNodes(TreeNode root) {
int ans = dfs(root);
return ans;
}
int maxL = 0;
int maxR = 0;
int countL = 0;
int countR = 0;
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int valL = dfs(root.left);
if (valL > root.val) {
countL++;
}
else {
if(root.val > maxL) {
countL = 0;
maxL = root.val;
}
else{
countL = countL;
}
}
int valR = dfs(root.right);
if (valR > root.val) {
countR++;
}
else {
if (root.val > maxR) {
countR = 0;
maxR = root.val;
}
else {
countL = countL;
}
}
return countR + countL;
}
}
I'm not sure why. Is it because I'm initialising the four variables outside it as 0 and that's the value it holds on to when called from the method goodNodes? I'd really appreciate if someone could point out the exact error in my logic here.
I set the count to 0 whenever I encounter a node whose maxL or maxR is less than it because it means that all the nodes before the current node cannot be counted as good nodes if the max node itself is being exceeded in value by this current node.
What is my mistake?
Источник: https://stackoverflow.com/questions/781 ... inary-tree