LeetCode-230. Kth Smallest Element in a BST (JAVA)二叉树第k小的数字

230. Kth Smallest Element in a BST

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.

BST中第k小的数字,中序遍历,没啥好说的。

	private TreeNode temp;
	private int counter;

	public int kthSmallest(TreeNode root, int k) {
		inorder(root, k);
		return temp.val;
	}

	public void inorder(TreeNode node, int k) {
		// perform in order tree traversal
		if (node == null)
			return; // base case
		inorder(node.left, k);
		if (++counter == k) {
			temp = node;
			return;
		}
		inorder(node.right, k);
	}

迭代:

	// k输入有效,中序遍历
	public int kthSmallest(TreeNode root, int k) {
		Stack stk = new Stack<>();
		while (root != null || !stk.isEmpty()) {
			if (root != null) {
				stk.push(root);
				root = root.left;
			} else {
				root = stk.pop();
				if (--k == 0)
					return root.val;
				root = root.right;
			}
		}
		// 此题k输入合法,不会到达这里
		return Integer.MIN_VALUE;

	}

你可能感兴趣的:(leetcode)