剑指Offer_62 发表于 2017-12-06 | 分类于 剑指Offer 题目给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。 解题思路中序遍历的结果就是二叉搜索树排序之后的结果。 解法一: 递归版本 1234//防止返回nullif(node != null){ return node;} 1234567891011121314151617181920212223242526272829303132333435363738/*public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { private int index = 0; TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot != null){ //首先程序递归到最左子树节点 TreeNode node = KthNode(pRoot.left, k); if(node != null){ return node; } //从最左子树节点开始计算 ++index; if(k == index){ return pRoot; } //弹出栈的节点访问它的右子树 node = KthNode(pRoot.right, k); if(node != null){ return node; } } return null; }} 解法二: 非递归版本 123456789101112131415161718192021222324252627282930313233343536373839404142434445import java.util.Stack;/*public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot == null || k <= 0){ return null; } Stack<TreeNode> stack = new Stack<>(); do{ //每次循环先 先将非空pRoot入栈 if(pRoot != null){ stack.push(pRoot); pRoot = pRoot.left; } else{ //出栈开始遍历,--k pRoot = stack.pop(); if(--k == 0){ return pRoot; } //上面是将节点的左子树入栈 //如果节点的右子树非空,那么就有机会入栈 pRoot = pRoot.right; } }while(pRoot != null || !stack.isEmpty()); return null; }}