-
230. Kth Smallest Element in a BSTAlgorithm/java tip 2021. 3. 24. 00:25
leetcode.com/problems/kth-smallest-element-in-a-bst/submissions/
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ // inorder with counting class Solution { int cnt = 0; int ans; public int kthSmallest(TreeNode root, int k) { inorder(root, k); return ans; } public void inorder(TreeNode node, int k) { if(node == null) return; if(cnt == k) return; inorder(node.left, k); cnt++; if(cnt == k) { ans = node.val; return; } inorder(node.right, k); } }
'Algorithm > java tip' 카테고리의 다른 글
238. Product of Array Except Self (0) 2021.03.24 347. Top K Frequent Elements (0) 2021.03.24 198. House Robber (0) 2021.03.23 1387. Sort Integers by The Power Value (0) 2021.03.21 1557. Minimum Number of Vertices to Reach All Nodes (0) 2021.03.20