在二叉搜索树查找第k大的结点

给定一颗二叉搜索树,查找第k大的结点

public static int KthSmallest(TreeNode root, int k)
        {
            Stack<TreeNode> s = new Stack<TreeNode>();
            TreeNode p = root;
            while (s.Count > 0 || p != null)
            {
                if (p != null)
                {
                    s.Push(p);
                    p = p.Left;
                }
                else
                {
                    p = s.Pop();
                    --k;
                    if (k == 0)
                    {
                        return p.value;
                    }
                    p = p.Right;
                }
            }
            return -1;
        }

猜你喜欢

转载自blog.csdn.net/smj20170417/article/details/80270532
今日推荐