JZ62 --- 序列化二叉树

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

题解:
根据二叉树的特性,可知中序遍历搜索二叉树得到的序列是有序的。
可以利用此特性来解决这个问题。

解法一:递归

public class Solution {

    TreeNode kNode = null;
    int count = 0;
    private void help(TreeNode root, int k) {
        if(root == null){
            return;
        }
        help (root.left,k);
        count++;
        if(count == k){
            kNode = root;
            return;
        }
        if(count > k){
            return;
        }else{
            help (root.right,k);
        }
    }

    TreeNode KthNode(TreeNode pRoot, int k) {
        if(pRoot == null || k <= 0){
            return null;
        }
        help(pRoot,k);
        return kNode;
    }
}

解法二:非递归,利用栈。

TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot == null || k <= 0){
            return null;
        }
        Stack<TreeNode> stack = new Stack<>(); //建立栈
        TreeNode cur = pRoot;
        //while 部分为中序遍历
        while(!stack.isEmpty() || cur != null){
            if(cur != null){
                stack.push(cur); //当前节点不为null,应该寻找左儿子
                cur = cur.left;
            }else{
            	当前节点null则弹出栈内元素,相当于按顺序输出最小值。
                cur = stack.pop();
                if(--k == 0){ //计数器功能
                    return cur;
                }
                cur = cur.right;
            }
        }
        return null;
    }

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