[Leetcode][Medium] Count Good Nodes in Binary Tree 统计二叉树中好节点的数目 | Java

2,654 阅读2分钟

问题

Count Good Nodes in Binary Tree Medium

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].

解题思路

判断当前节点是否为好节点,只需要知道该节点所有的祖先节点,跟它的兄弟节点没有关系。因此,我们可以使用DFS深度优先搜索来遍历整棵树。

当我们判断某一个节点时,如果它的父节点是好节点,那么它只要大于等于父节点,就是好节点。如果父节点不是好节点,那么就要跟找到离它最近的好的祖先节点,然后进行比较。因为比较是单向的,我们只要在DFS的过程中记录上次找到的好节点(或者好节点的值),就可以很简单地找到最近的好的祖先节点进行比较。

参考答案

public class Solution {
    int cnt;
    
    public int goodNodes(TreeNode root) {
        cnt = 0;
        // search from root
        DFS(root, null);
        return cnt;
    }

    void DFS(TreeNode node, TreeNode lastGoodNode) {
        // current node is good or not
        boolean isGood = false;
        // lastGoodNode == null means current node is root and need to be counted
        // when it's not root and node.val >= lastGoodNode.val then count
        if (lastGoodNode == null || node.val >= lastGoodNode.val) {
            cnt++;
            isGood = true;
        }
        
        if (node.left != null) {
            DFS(node.left, isGood ? node : lastGoodNode);
        }
        if (node.right != null) {
            DFS(node.right, isGood ? node : lastGoodNode);
        }
    }
}

image.png

拓展训练

来试试这个同样使用的DFS的问题吧!

[LeetCode][Hard] Making A Large Island 最大人工岛 | Java

或者到作者的LeetCode专栏中看看,有没有其他感兴趣的问题吧!

juejin.cn/column/6997…

资料链接

原题 leetcode.com/problems/co…

深度优先搜索 zh.wikipedia.org/wiki/%E6%B7…