LeetCode 230. Kth Smallest Element in a BST

来源:互联网 发布:h5砸金蛋游戏源码 编辑:程序博客网 时间:2024/06/07 14:18
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int kthSmallest(TreeNode root, int k) {        Stack<TreeNode> stack = new Stack<TreeNode>();    while (root != null) {    stack.push(root);    root = root.left;    }    while (k != 0) {    TreeNode n = stack.pop();    if (--k == 0) return n.val;    n = n.right;    while (n != null) {    stack.push(n);    n = n.left;    }    }    return Integer.MIN_VALUE;    }}

0 0
原创粉丝点击