一刷 05/2022
Version #1 Iteration with Stack
/**
* 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 kthSmallest(TreeNode root, int k) {
// Use stack to do a in order traversal of the tree
Stack<TreeNode> stack = new Stack<>();
pushLeft(root, stack);
TreeNode curr = null;
while (!stack.isEmpty() && k > 0) {
curr = stack.pop();
pushLeft(curr.right, stack);
k--;
}
return curr.val;
}
private void pushLeft(TreeNode node, Stack<TreeNode> stack) {
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
Version #2 Recursion
/**
* 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 kthSmallest(TreeNode root, int k) {
int[] count = new int[]{k};
int[] result = new int[]{-1};
helper(root, count, result);
return result[0];
}
private void helper(TreeNode node, int[] count, int[] result) {
if (node == null) {
return;
}
helper(node.left, count, result);
if (result[0] != -1) {
return;
}
if (count[0] == 1) {
result[0] = node.val;
return;
}
count[0]--;
helper(node.right, count, result);
}
}
No comments:
Post a Comment