-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackIterative.php
45 lines (39 loc) · 1.1 KB
/
StackIterative.php
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
<?php
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @param Integer $k
* @return Integer
*/
function kthSmallest($root, $k) {
$stack = [];
$current = $root ;
while($stack or $current){
// first walk to the left
while ($current){
$stack[] = $current;
$current = $current->left ;
}
// then pop from stack the last left
$current = array_pop($stack);
$k--; //decrease $k because we poped one left
// we reached the k smallest
if($k == 0) return $current->val ;
// if nothing happens walk to right from the last left position
$current = $current->right ;
}
}
}