Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
采用中序遍历的方法,找到第K小的数。考察理解BST的特性。
非递归中序遍历:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int kthSmallest(TreeNode root, int k) { 12 Stack<TreeNode> stack = new Stack<>(); 13 TreeNode curt = root; 14 while (!stack.empty() || curt != null) { 15 while (curt != null) { 16 stack.push(curt); 17 curt = curt.left; 18 } 19 curt = stack.pop(); 20 --k; 21 if (k == 0) { 22 return curt.val; 23 } 24 curt = curt.right; 25 } 26 return -1; 27 } 28 }
中序遍历递归:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 private int result = 0; 12 private int count = 0; 13 public int kthSmallest(TreeNode root, int k) { 14 count = k; 15 helper(root); 16 return result; 17 } 18 19 private void helper(TreeNode root) { 20 if (root == null) { 21 return; 22 } 23 if (root.left != null) { 24 helper(root.left); 25 } 26 --count; 27 if (count == 0) { 28 result = root.val; 29 return; 30 } 31 if (root.right != null) { 32 helper(root.right); 33 } 34 } 35 }
分别统计左子树的节点数和右子树的节点数,根据左右子树的节点数与K的大小关系,知道第K小的数在左子树还是右子树。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int kthSmallest(TreeNode root, int k) { 12 int count = countNodes(root.left); 13 if (k <= count) { 14 return kthSmallest(root.left, k); 15 } else if (k > count + 1) { 16 return kthSmallest(root.right, k - count - 1); 17 } else { 18 //count + 1 == k 19 return root.val; 20 } 21 } 22 23 private int countNodes(TreeNode root){ 24 if(root == null) { 25 return 0; 26 } 27 return 1 + countNodes(root.left) + countNodes(root.right); 28 } 29 }