Kth Smallest Element in a BST

来源:互联网 发布:c语言竖线 编辑:程序博客网 时间:2024/06/05 02:44
/** * 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) {        if (root == null) {            return 0;        }        Stack<TreeNode> stack = new Stack<>();        stack.push(root);        int i = 0;        while (!stack.isEmpty()) {            TreeNode node = stack.peek();            if (node.left != null) {                stack.push(node.left);                node.left = null;            } else {                stack.pop();                i++;                if (i == k) {                    return node.val;                }                if (node.right != null) {                    stack.push(node.right);                }            }        }        return 0;    }}

0 0
原创粉丝点击