【剑指offer】求二叉搜索树的第k个结点

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

 * 示例1
 * 输入{5,3,7,2,4,6,8},3
 * 返回值{4}
 * <p>
 * 说明
 * 按结点数值大小顺序第三小结点的值为4

声明TreeNode节点:

public class TreeNode {

    public int value;
    public TreeNode left;
    public TreeNode right;

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

求第k小TreeNode节点

/**
 * https://blog.nowcoder.net/n/fa683a00f1a8445cad7c09f91b538265?f=comment
 */
public class The_K_st_TreeNode {
    //方法一:
    ArrayList<TreeNode> list = new ArrayList<>();

    /**
     * 递归中序遍历
     *
     * @param pRoot
     * @param k
     * @return
     */
    TreeNode KthNode(TreeNode pRoot, int k) {
        if (k == 0) return null;
        inOrderTree(pRoot);
        if (list.size() < k) return null;
        return list.get(k - 1);
    }

    public void inOrderTree(TreeNode pRoot) {
        if (pRoot != null) {
            inOrderTree(pRoot.left);
            list.add(pRoot);
            inOrderTree(pRoot.right);
        }
    }

    //方法二:

    TreeNode KthNode1(TreeNode pRoot, int k) {
        if (pRoot == null || k <= 0) {
            return null;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || pRoot != null) {
            while (pRoot != null) {
                stack.push(pRoot);
                pRoot = pRoot.left;
            }
            //从栈中取出节点 并赋值给pRoot
            pRoot = stack.pop();
            if (--k == 0) {
                return pRoot;
            }
            pRoot = pRoot.right;
        }
        return null;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值