-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.rb
More file actions
67 lines (43 loc) · 876 Bytes
/
Solution.rb
File metadata and controls
67 lines (43 loc) · 876 Bytes
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
# Definition for a binary tree node.
class TreeNode
attr_accessor :val, :left, :right
def initialize(val)
@val = val
@left, @right = nil, nil
end
end
# @param {TreeNode} root
# @param {Integer} k
# @return {Integer}
def kth_smallest(root, k)
if root.nil?
return -1
end
ptr = root
node_stack = Array.new
k_count = 0
until k_count == k
if ptr.nil?
ptr = node_stack.pop
k_count += 1
if k_count == k
break
end
ptr = ptr.right
else
node_stack.push ptr
ptr = ptr.left
end
end
ptr.val
end
tree = TreeNode.new 4
tree.left = TreeNode.new 2
tree.left.left = TreeNode.new 1
tree.left.right = TreeNode.new 3
tree.right = TreeNode.new 6
tree.right.left = TreeNode.new 5
tree.right.right = TreeNode.new 7
# tree = TreeNode.new 1
target = kth_smallest tree, 6
puts target