Kth Smallest Element in a BST

来源:互联网 发布:形容网络不好的说说 编辑:程序博客网 时间:2024/06/07 02:57

题意:

给定一棵二叉查找树,找出第k大的元素;

分析:

二叉查找树中序遍历正好是有序的,找到第k个即可

/** * 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) {        Stack<TreeNode> stack = new Stack<TreeNode>();        int cnt = 0;        TreeNode p = root, q = null;        while(p != null || !stack.empty()){            if(p != null){                stack.push(p);                p = p.left;            }            else{                p = stack.peek();                stack.pop();                cnt++;                if(cnt == k){                    q = p;                    break;                }                p = p.right;            }        }                return q.val;    }}


0 0