54_KthNodeInBST

package pers.lyt.java;

import java.util.Stack;

//题目
//	给定一棵二叉搜索树,请找出其中的第k小的结点。
//思路
//	设置全局变量index=0,对BST进行中序遍历,每遍历一个结点,index+1,当index=k时,
//该结点即为所求结点。
public class Offer54_KthNodeInBST {
	public class TreeNode {
		int val = 0;
		TreeNode left = null;
		TreeNode right = null;

		public TreeNode(int val) {
			this.val = val;
		}
	}

	/**
	 * 方法一:利用辅助栈遍历二叉搜索树
	 */
	public TreeNode KthNode1(TreeNode root, int k) {
		if (root == null || k <= 0)
			return null;
		int index = 0;
		Stack<TreeNode> stack = new Stack<>();
		while (root != null || !stack.empty()) {
			while (root != null) {
				stack.push(root);
				root = root.left;
			}
			root = stack.pop();
			index++;
			if (index == k)
				return root;
			root = root.right;
		}
		return null;
	}

	/**
	 * 方法二:递归
	 */
	public TreeNode KthNode(TreeNode pRoot, int k) {
		TreeNode pNode = null;
		if (pRoot == null || k <= 0)
			return pNode;
		pNode = getKthNode(pRoot, k);
		return pNode;
	}

	int index = 0;

	// 与和辅助栈遍历有相似之处
	private TreeNode getKthNode(TreeNode pRoot, int k) {
		if (pRoot == null)
			return null;
		TreeNode kthNode = null;

		kthNode = getKthNode(pRoot.left, k);
		index++;
		if (k == index)
			kthNode = pRoot;
		if (kthNode == null) // kthNode不为null直接返回即可
			kthNode = getKthNode(pRoot.right, k);

		return kthNode;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值