leetcode1448. 统计二叉树中好节点的数目(dfs)

给你一棵根为 root 的二叉树,请你返回二叉树中好节点的数目。

「好节点」X 定义为:从根到该节点 X 所经过的节点中,没有任何节点的值大于 X 的值。

代码

/**
 * 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 {
    int nodes=0;
    public int goodNodes(TreeNode root) {
        good(root,root.val);
        return nodes;
    }
    public void good(TreeNode root,int max) {
         if(root==null) return;
         if(root.val>=max)//路径上的最大值判断
         {
             nodes++;
             max=root.val;
         }
         good(root.left,max);
         good(root.right,max);
    }
}

你可能感兴趣的:(leetcode,二叉树,算法,leetcode,数据结构)