剑指offer—二叉搜索树的第k个结点

来源:互联网 发布:mac aegisub 乱码 编辑:程序博客网 时间:2024/05/22 09:50

题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

import java.util.ArrayList;public class Solution {    ArrayList<TreeNode> res = new ArrayList<TreeNode>();    int index = 0;    public TreeNode KthNode(TreeNode pRoot, int k)    {        if(pRoot==null || k<=0) return null;        KthNodeHelper(pRoot,k);        if(res.size()<=0)            return null;        return res.get(0);    }    public void KthNodeHelper(TreeNode pRoot, int k){        if(pRoot!=null){            KthNodeHelper(pRoot.left,k);            index++;            if(index==k){                res.add(pRoot);            }            KthNodeHelper(pRoot.right,k);        }    }}

中序遍历顺序是按照递增顺序排列的,按照中序遍历顺序遍历二叉树,保存第K个结点的值返回即可

阅读全文
0 0
原创粉丝点击