二叉搜索树的第k个结点

来源:互联网 发布:淘宝买处方药流程 编辑:程序博客网 时间:2024/05/17 22:06

题目

给定一颗二叉搜索树,请找出其中的第k大的结点。

解题

中序遍历时候找到第k大结点

import java.util.ArrayList;public class Solution {    ArrayList<TreeNode> list = new ArrayList<TreeNode>();    TreeNode KthNode(TreeNode pRoot, int k)    {        inorder(pRoot);        if(k<=0 || k> list.size())            return null;        return list.get(k-1);    }    public void inorder(TreeNode root){        if(root == null)            return;        inorder(root.left);        list.add(root);        inorder(root.right);    }}

利用中序遍历,记录遍历结点个数找到第k个结点

/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/public class Solution {    int count = 0; // 记录遍历结点个数    TreeNode KthNode(TreeNode root, int k)    {        if(root==null|| k<=0)            return null;        TreeNode left = KthNode(root.left,k);        if(left!=null)            return left;        count++;        if(count == k)            return root;        TreeNode right = KthNode(root.right,k);        if(right!=null)            return right;        return null;    }}
0 0
原创粉丝点击