Sponsored
Sponsored
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Space Complexity: O(h), where h is the height of the tree due to the recursion stack.
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def dfs(self, node, maxVal):
9 if not node:
10 return 0
11 good = 1 if node.val >= maxVal else 0
12 maxVal = max(maxVal, node.val)
13 return good + self.dfs(node.left, maxVal) + self.dfs(node.right, maxVal)
14
15 def goodNodes(self, root):
16 return self.dfs(root, root.val)
17
This Python solution utilizes a helper function dfs
within the class Solution
. It employs recursion to traverse the tree and count the good nodes as per the conditions provided.
Time Complexity: O(n), where n is the number of nodes in the tree.
Space Complexity: O(w), where w is the maximum width of the tree.
using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public int GoodNodes(TreeNode root) {
if (root == null) return 0;
Queue<(TreeNode, int)> queue = new Queue<(TreeNode, int)>();
queue.Enqueue((root, root.val));
int goodCount = 0;
while (queue.Count > 0) {
(TreeNode node, int maxVal) = queue.Dequeue();
if (node.val >= maxVal) goodCount++;
if (node.left != null) queue.Enqueue((node.left, Math.Max(maxVal, node.val)));
if (node.right != null) queue.Enqueue((node.right, Math.Max(maxVal, node.val)));
}
return goodCount;
}
}
In this C# solution, a queue is used to implement BFS, with each item being a tuple that contains both the current node and the maximum value encountered so far. The process checks each node, updating the count of good nodes as necessary.