You are given the root of a binary tree (not a BST, just a generic binary tree) and a target value x. Count how many nodes in the tree have node.val == x.
Implement a recursive function to count the occurrences of the target value x in the binary tree.
Implement an iterative function to count the occurrences of the target value x in the binary tree.
0 and 10^4.0 and 10^9.Input:
1 / \ 2 3 / \ 4 5x = 3Output:
1 (There is one node with value 3).Input:
1 / \ 2 3 / \ 4 5x = 1Output:
1 (There is one node with value 1).Input:
1 / \ 2 3 / \ 4 5x = 4Output:
1 (There is one node with value 4).`python class TreeNode: def init(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
def countValueRecur(root, x): if not root: return 0 return (root.val == x) + countValueRecur(root.left, x) + countValueRecur(root.right, x) `
`python from collections import deque
def countValueIter(root, x): if not root: return 0 queue = deque([root]) count = 0 while queue: node = queue.popleft() if node.val == x: count += 1 if node.left: queue.append(node.left) if node.right: queue.append(node.right) return count `