剑指offer:二叉搜索树的第k个结点(考点:中序遍历)

题目:给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

分析:采用中序遍历二叉搜索树,得到的遍历顺序为递增顺序,易得到第k大结点

解法一:采用非递归中序遍历

TreeNode KthNode(TreeNode pRoot, int k) {
        if(pRoot==null||k<0){
            return null;
        }
        TreeNode curNode=pRoot; //指向当前节点
        TreeNode KNode=null;
        int count=0;
        LinkedList stack=new LinkedList<>();
        //中序遍历二叉树
        while(!stack.isEmpty()||curNode!=null){
            while(curNode!=null){
                stack.push(curNode);
                curNode=curNode.left;
            }
            if(!stack.isEmpty()){
                curNode=stack.pop();
                count++;
                if(k==count){
                    KNode=curNode;
                    break;
                }
                curNode=curNode.right;
            }
        }
        return KNode;
    }

解法二:递归中序遍历

//递归中序遍历
    int count=0;
    TreeNode KthNode1(TreeNode pRoot, int k) {
        if(pRoot==null||k<0){
            return null;
        }
        TreeNode target=null;
        if(pRoot.left!=null){
            target = KthNode1(pRoot.left,k);
        }
        count++;
        if(target==null){
            if(count==k){
                target=pRoot;
                return target;
            }
        }
        if(target==null&&pRoot.right!=null){
            target=KthNode1(pRoot.right,k);
        }
        return target;
    }

你可能感兴趣的:(剑指offer)