File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ ### Binary Tree / Binary Search Tree
2
+
3
+ ** Count number of nodes **
4
+ ``` kotlin
5
+ class Solution {
6
+ // I need to traverse the tree in in-order manner
7
+ fun numberOfNodes (root : TreeNode ? ): Int {
8
+ fun dfs (node : TreeNode ? , counter : Int ): Int {
9
+ if (node == null ) return counter
10
+ val left = dfs(node.left, counter)
11
+ return left + dfs(node.right, left + 1 )
12
+ }
13
+
14
+ return dfs(root, 0 )
15
+ }
16
+ }
17
+ ```
18
+
19
+ ** Find kth element in the tree **
20
+ ``` kotlin
21
+ class Solution {
22
+ fun kthSmallest (root : TreeNode ? , k : Int ): Int {
23
+ if (root == null ) return - 1
24
+ var kthSmallestElement = 0
25
+
26
+ fun dfs (node : TreeNode ? , counter : Int ): Int {
27
+ if (node == null ) return counter
28
+ val left = dfs(node.left, counter)
29
+ val mid = left + 1
30
+ if (mid == k) {
31
+ kthSmallestElement = node.`val `
32
+ }
33
+ val right = dfs(node.right, mid)
34
+ return right
35
+ }
36
+
37
+ dfs(root, 0 )
38
+
39
+ return kthSmallestElement
40
+ }
41
+ }
42
+ ```
You can’t perform that action at this time.
0 commit comments