-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoodnode.java
More file actions
101 lines (87 loc) · 2.06 KB
/
Goodnode.java
File metadata and controls
101 lines (87 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*Count Good Nodes in Binary Tree
Solved
Within a binary tree, a node x is considered good if the path from the root of the tree to the node x contains no nodes with a value greater than the value of node x
Given the root of a binary tree root, return the number of good nodes within the tree.
Example 1:
Input: root = [2,1,1,3,null,1,5]
Output: 3
Example 2:
Input: root = [1,2,-1,3,4]
Output: 4
Constraints:
1 <= number of nodes in the tree <= 100
-100 <= Node.val <= 100
*/
/**
* 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 count=0;
public int goodNodes(TreeNode root) {
int key=root.val;
inorder(root,key);
return count;
}
void inorder(TreeNode root,int key)
{
if(root!=null)
{
if(root.val>=key)
{
count++;
key=root.val;
}
inorder(root.left,key);
inorder(root.right,key);
}
}
}
/**
* 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 count=0;
public int goodNodes(TreeNode root) {
int key=root.val;
inorder(root,key);
return count;
}
void inorder(TreeNode root,int key)
{
if(root!=null)
{
if(root.val>=key)
{
count++;
key=root.val;
}
inorder(root.left,key);
inorder(root.right,key);
}
}
}
//TIMECOMPLECITY:O(n)