统计二叉树中好节点的数目【LC1448】
给你一棵根为
root
的二叉树,请你返回二叉树中好节点的数目。「好节点」X 定义为:从根到该节点 X 所经过的节点中,没有任何节点的值大于 X 的值。
-
思路:dfs
维护当前路径所有父节点中的最大值,如果最大值小于等于当前节点,那么更新最大值,数量+1;并递归至左右子树
-
实现
/** * 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) { return dfs(root, Integer.MIN_VALUE); } public int dfs(TreeNode root, int mx){ if (root == null) return 0; int res = 0; if (root.val >= mx){ res += 1; mx = root.val; } mx = Math.max(mx, root.val); res += dfs(root.left, mx); res += dfs(root.right, mx); return res; } }
- 复杂度
- 时间复杂度: O ( n ) \mathcal{O}(n) O(n)
- 空间复杂度: O ( n ) \mathcal{O}(n) O(n)
- 复杂度