Kth Smallest Element in a BST

来源:互联网 发布:mac开启root权限 编辑:程序博客网 时间:2024/06/07 13:22

工作时做一道题好难。。。

最基本的中序遍历!

/** * 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 count = 1;        while (!stack.isEmpty()) {            TreeNode node = stack.peek();            if (node.left != null) {                stack.push(node.left);                node.left = null;            } else {                if (count == k) {                    return node.val;                }                count++;                stack.pop();                if (node.right != null) {                    stack.push(node.right);                }            }        }        return 0;    }}


0 0