64 K-ノードバイナリ検索ツリー

件名の説明:

  二分探索木を考えると、その中の最初のk小さいノードを検索してください。例えば、(5,3,7,2,4,6,8)と、第3の接続点に係る数値は、4要約です。

アイデアの分析:

  二分探索木の特徴によれば、我々は、配列プレオーダーが生成順序付けられたシーケンスであり、第1の点を横断するために、第1のK K小さいノードです。

コード:

import java.util.*;
/*
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;
        TreeNode pNode=pRoot;
        Stack<TreeNode>s=new Stack<>();
        int count=0;
        while(pNode!=null||!s.isEmpty()){
            while(pNode!=null){
                s.push(pNode);
                pNode=pNode.left;
            }
            if(!s.isEmpty()){
                pNode=s.pop();
                count++;
                if(count==k)
                    return pNode;
                pNode=pNode.right;
            }
        }
        return null;
    }


}

おすすめ

転載: www.cnblogs.com/yjxyy/p/10962599.html
おすすめ