Kth Smallest Element in a BST

来源:互联网 发布:淘宝店铺层级怎么计算 编辑:程序博客网 时间:2024/04/25 22:14

思路:
1 . 可以设置一个全局变量 , 中序遍历即可
2. 不是递归总序遍历,而是迭代式

public class Solution {    public int kthSmallest(TreeNode root, int k) {        LinkedList<TreeNode> stack = new LinkedList<> ();        stack = getLeft(root);        int idx = 0;        while(!stack.isEmpty()) {            TreeNode node = stack.removeLast();            idx++;            if(node.right != null) stack.addAll(getLeft(node.right));            if(idx == k) return node.val;        }        return 0;    }    LinkedList<TreeNode> getLeft(TreeNode root) {        LinkedList<TreeNode> list = new LinkedList<> ();        while(root != null) {            list.addLast(root);            root = root.left;        }        return list;    }}
0 0