[LeetCode 解題紀錄] 1448. Count Good Nodes in Binary Tree

Sean Chou
Recording everything
5 min readJun 19, 2024

--

1448. Count Good Nodes in Binary Tree

https://leetcode.com/problems/count-good-nodes-in-binary-tree/

Problem:

Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

Return the number of good nodes in the binary tree.

Example 1:

Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.

Example 2:

Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.

Example 3:

Input: root = [1]
Output: 1
Explanation: Root is considered as good.

Constraints:

  • The number of nodes in the binary tree is in the range [1, 10^5].
  • Each node’s value is between [-10^4, 10^4].

題意

這題的的意蠻容易理解的,目的要找出這顆 Tree 當中的「Good Node」有多少個,「Good Node」的定義就是,從某個節點往回找到 root 之中,經過的節點值都小於等於此節點,這個節點就是「Good Node」。

問題解析

首先,我們可以使用 DFS 的方式,來遍歷整顆 Tree,而要找到「經過的節點值都小於等於此節點」,其實就等於每一個節點要檢查「此路徑從父節點來的所有節點最大值」有沒有小於等於此節點的值,有的話這時候就可以把紀錄 +1,最後回傳這個紀錄值即可。

解法

DFS (Depth-First-Search)

如上述問題解析的部分提到的,我們可以使用 DFS 來對每一個節點做「此路徑從父節點來的所有節點最大值」的檢查。

Tree 與 DFS 概念複習:

  1. 定義一個計入最終結果的 numOfGoodNodes ,初始為 0。
  2. 定義一個用來遍歷的 dfs函數 findGoodNodes ,參數需傳入一個節點與此節點往前找到 root 最大的值 maxParentValue
  • 如果當前節點值大於等於 maxParentValuenumOfGoodNodes增加 1
  • 如果當前節點的左子樹不等於空,遞迴 findGoodNodes
  • 如果當前節點的右子樹不等於空,遞迴 findGoodNodes

最後回傳 numOfGoodNodes

/**
* @param {TreeNode} root
* @return {number}
*/
var goodNodes = function(root) {
let numOfGoodNodes = 0;

const findGoodNodes = (node, maxParentValue) => {
if (node.val >= maxParentValue) {
numOfGoodNodes ++;
}
const maxValue = Math.max(maxParentValue, node.val);
if (node.left !== null) {
findGoodNodes(node.left, maxValue)
}
if (node.right !== null) {
findGoodNodes(node.right, maxValue)
}
}

findGoodNodes(root, root.val);

return numOfGoodNodes;
};
  • 時間複雜度:O(n)
  • 空間複雜度:O(h),h 為樹的高度

--

--