劍指Offer-二叉搜索樹的第K個節點

36.二叉搜索樹的第K個節點

給定一棵二叉搜索樹,請找出其中的第k小的結點。

你可以假設樹和k都存在,並且1≤k≤樹的總結點數。

樣例

輸入:root = [2, 1, 3, null, null, null, null] ,k = 3

    2
   / \
  1   3

輸出:3

思路

中序遍歷二叉樹序列的第k個節點就是第k小的節點。

class Solution {
    //計數
    int count=0;
    //存放結果
    TreeNode kNode=null;
    public TreeNode kthNode(TreeNode root, int k) {
        if(root==null || k<0) return null;
        kthNode(root.left,k);
        count++;
        if(count==k) kNode=root;
        kthNode(root.right,k);
        return kNode;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章