Leetcode 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.
在这里插入图片描述

method 1

树的问题一般即树的遍历问题,考虑前序、中序、后序和层序
根据题目意思,可以从小到大遍历二叉树,那么得到便是一串从小到大的序列,第k个即为所求,所以使用中序,并使用一个数组存储

void inOrder(TreeNode* root, int k, vector<int> vals){
	if (!root) return;

	inOrder(root->left, k, vals);
	vals.push_back(root->val);
	inOrder(root->right, k, vals);
}

int kthSmallest(TreeNode* root, int k) {
	vector<int> vals;
	inOrder(root, k, vals);
	return vals[k-1];
}

method 2

同样的思想,不过借助一个stack实现迭代(非递归)的方法

class Solution {
  public int kthSmallest(TreeNode root, int k) {
    LinkedList<TreeNode> stack = new LinkedList<TreeNode>();

    while (true) {
      while (root != null) {
        stack.add(root);
        root = root.left;
      }
      root = stack.removeLast();
      if (--k == 0) return root.val;
      root = root.right;
    }
  }
}

summary

  1. 树的问题一般可以归纳为树的遍历顺序问题!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值