230. Kth Smallest Element in a BST
Posted tobeabetterpig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了230. Kth Smallest Element in a BST相关的知识,希望对你有一定的参考价值。
230. Kth Smallest Element in a BST // dfs inroder traversal recursively , record the first k nodes , return the kth node Solution { List<Integer> result = new ArrayList<>(); public int kthSmallest(TreeNode root, int k) { if(root == null){ return 0; } inorder(root, k); return result.get(k - 1); } private void inorder(TreeNode root, int k){ if(result.size() >= k){ return; } if(root == null){ return; } inorder(root.left, k); result.add(root.val); inorder(root.right, k); } } DFS in-order recursive : idk the confusion discussed in class and don’t know how to write this recursively // inroder traversal recursively, no need to record the the first k-1 elements , only return the kth public class Solution { public int kthSmallest(TreeNode root, int k) { List<Integer> res = new ArrayList<>(); inOrder(res, root, k); return res.size() >= k ? res.get(k - 1) : 0; } private void inOrder(List<Integer> res, TreeNode root, int k) { if (root == null || res.size() >= k) return; inOrder(res, root.left, k); res.add(root.val); inOrder(res, root.right, k); } } DFS in-order iterative: public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> st = new Stack<>(); while (root != null) { st.push(root); root = root.left; } while (k != 0) { TreeNode n = st.pop(); k--; if (k == 0) return n.val; TreeNode right = n.right; while (right != null) { st.push(right); right = right.left; } } return -1; // never hit if k is valid } 这个不是自己写的, 自己写的 会叫 pushleft, 虽然都是一样的, 但是要自己写, 自己理解的。。 Binary Search (dfs): most preferable I don’t understand this solution, might be discussed in the future bst class public int kthSmallest(TreeNode root, int k) { int count = countNodes(root.left); if (k <= count) { return kthSmallest(root.left, k); } else if (k > count + 1) { return kthSmallest(root.right, k-1-count); // 1 is counted as current node } return root.val; } public int countNodes(TreeNode n) { if (n == null) return 0; return 1 + countNodes(n.left) + countNodes(n.right); }
以上是关于230. Kth Smallest Element in a BST的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 230. Kth Smallest Element in a BST
Leetcode 230. Kth Smallest Element in a BST
230. Kth Smallest Element in a BST
230.Kth Smallest Element in a BST