TreeviewCopyright © aleen42 all right reserved, powered by aleen42

1448. 统计二叉树中好节点的数目

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

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-09-23 21:53:11
 * @LastEditTime: 2020-09-23 21:54:08
 * @Description: https://leetcode-cn.com/problems/count-good-nodes-in-binary-tree/
 * @FilePath: \leetcode-googtech\#1448. Count Good Nodes in Binary Tree\Solution.java
 * @WebSite: https://algorithm.show/
 */

/**
 * 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 {
    private int result = 0;

    // DFS : 深度优先搜索
    public int goodNodes(TreeNode root) {
        dfs(root, root.val);
        return result;
    }
    private void dfs(TreeNode node, int max) {
        if(node == null) return;
        if(node.val >= max) {
            max = node.val;
            result++;
        }
        dfs(node.left, max);
        dfs(node.right, max);
    }
}

Python

'''
Author: Goog Tech
Date: 2020-09-23 21:53:15
LastEditTime: 2020-09-23 21:54:24
Description: https://leetcode-cn.com/problems/count-good-nodes-in-binary-tree/
FilePath: \leetcode-googtech\#1448. Count Good Nodes in Binary Tree\Solution.py
WebSite: https://algorithm.show/
'''

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution(object):

    # DFS : 深度优先遍历
    def goodNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.result = 0
        def dfs(node, maxValue):
            if not node: return
            if node.val >= maxValue:
                maxValue = node.val
                self.result += 1
            dfs(node.left, maxValue)
            dfs(node.right, maxValue)
        dfs(root, float('-inf'))
        return self.result
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""