首页 > 代码库 > 230. Kth Smallest Element in a BST
230. Kth Smallest Element in a BST
https://leetcode.com/problems/kth-smallest-element-in-a-bst/#/solutions
public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while(cur != null || !stack.isEmpty()){ while(cur != null){ stack.push(cur); cur = cur.left; } TreeNode node = stack.pop(); if(--k == 0) return node.val; cur = node.right; } return root.val; }
递归:
public class Solution { int count = 0; public int kthSmallest(TreeNode root, int k) { List<Integer> res = new ArrayList<Integer>(); res.add(null); helper(root, k, res); return res.get(0); } public void helper(TreeNode root, int k, List<Integer> res) { if (root == null) return; helper(root.left, k, res); count++; if (count == k) res.set(0, root.val); helper(root.right, k, res); } }
230. Kth Smallest Element in a BST
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。