剑指offer系列(62):二叉搜索树的第k个结点

题目描述

 

给定一棵二叉搜索树,请找出其中的第k小的结点。

 

样例

(5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

 

思路分析

方法一:递归法 二叉搜索树按照中序遍历的顺序 打印出来 即为升序排序 设置一计数器 进行中序排序 找到第k个 即可

方法二:非递归法 构造一个栈,思路同 中序遍历的非递归法

 

代码及结果

方法一:

int count = 0;
TreeNode ans;
TreeNode KthNode(TreeNode pRoot, int k){
		helper(pRoot, k);
		return ans;
    }
	
public void helper(TreeNode node, int k){
		if (node==null || count>k) {
			return;
		}
		helper(node.left, k);
		count++;
		if (count == k) {
			ans = node;
		}
		helper(node.right, k);
	}

 

方法二:

TreeNode KthNode(TreeNode pRoot, int k){
		if (pRoot == null) {
			return null;
		}
		int count = 0;
		Stack<TreeNode> stack = new Stack<TreeNode>();
		TreeNode temp = null;
		while (!stack.isEmpty() || pRoot!=null) {
			while (pRoot != null) {
				stack.push(pRoot);
				pRoot = pRoot.left;
			}
			TreeNode node = stack.pop();
			count++;
			if (count == k) {
				temp = node;
			}
			pRoot = node.right;
		}
		return temp;
	}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值