天天看点

Count Good Nodes in Binary Tree

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:

Count Good Nodes in Binary Tree
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.
           

思路:记住:tree的题,只有两种解法,1: traverse 2. Divide & Conquer.这题需要从上往下传递目前的最大值;注意传值,除了method return value之外,还可以参数传值;要连续递增的,那么也就是走到当前最大的值比root小就可以;把目前遇到的最大值往下传就可以;

错误点:传值,除了method递归传值,参数也可以传值;

/**
 * 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 {
    public int goodNodes(TreeNode root) {
        int[] res = {0};
        int prevalue = root.val;
        goodNodesHelper(root, res, prevalue);
        return res[0];
    }
    
    private void goodNodesHelper(TreeNode root, int[] res, int prevalue) {
        if(root == null) {
            return;
        }
        if(root.val >= prevalue) {
            prevalue = root.val;
            res[0]++;
        }
        goodNodesHelper(root.left, res, prevalue);
        goodNodesHelper(root.right, res, prevalue);
    }
}