Kth Smallest Element in a BST

解題思路:按樹的中序遍歷的方式,利用棧實現,第k個出棧的節點即是所求的。

Java 代碼實現:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        TreeNode p=new TreeNode(0);
        p=root;
        Stack sk=new Stack();
        sk.push(p);
        while(p.left!=null){
            sk.push(p.left);
            p=p.left;
        }
        int i=0;
        while(!sk.isEmpty()){
            TreeNode q=new TreeNode(0);
            q=(TreeNode)sk.pop();
            i++;
            if(i==k) return q.val;
            if(q.right!=null) {
                p=q.right;
                sk.push(p);
                while(p.left!=null){
                    sk.push(p.left);
                     p=p.left;
                }
            }
        }
        return 0;
    }
}

原題題目:https://leetcode.com/problems/kth-smallest-element-in-a-bst/


發佈了41 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章