博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指Offer——二叉搜索树中第K大的节点
阅读量:4227 次
发布时间:2019-05-26

本文共 1375 字,大约阅读时间需要 4 分钟。

题目描述:给定一颗二叉树,找出第K大的节点,这个第K大的节点是从小到大的第K个节点,所以也可以说是第K小的节点。对于一颗二叉树来说,其中序遍历就是节点值从小到大的排列,那么我们用一个ArrayList把中序遍历的结果保存下来,找到第K-1个节点就是第K大的节点。因此很容易想到以下的代码:

/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/import java.util.ArrayList;public class Solution {    TreeNode KthNode(TreeNode pRoot, int k)    {        //中序遍历的第k-1个节点就是第k大的节点        if(pRoot == null || k<=0)            return null;        ArrayList
aList = new ArrayList(); inOrderRecursive(pRoot,aList); int len = aList.size(); if(len
al){ if(root == null){ return; } inOrderRecursive(root.left,al); al.add(root); inOrderRecursive(root.right,al); }}
当然,也可以边遍历,边返回节点,这样可以提高效率,比如当这颗二叉树很大,但是K很小的时候,就会大大的节约时间。代码实现如下:
//思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。//     所以,按照中序遍历顺序找到第k个结点就是结果。public class Solution {   int index = 0; //计数器    TreeNode KthNode(TreeNode root, int k)    {        if(root != null){ //中序遍历寻找第k个            TreeNode node = KthNode(root.left,k);            if(node != null)                return node;            index ++;            if(index == k)                return root;            node = KthNode(root.right,k);            if(node != null)                return node;        }        return null;    }}

转载地址:http://psnqi.baihongyu.com/

你可能感兴趣的文章
嵌入式系统基础学习笔记(九):基于 SPI 协议在 0.96 寸 OLED上【平滑显示汉字】及【温湿度数据采集显示】
查看>>
嵌入式系统基础学习笔记(十):
查看>>
网络通信编程学习笔记(七):Java与MQTT
查看>>
人工智能与机器学习学习笔记(二)
查看>>
Java I/O
查看>>
SQL Server 2005 T-SQL Recipes: A Problem-Solution Approach
查看>>
Core Python Programming
查看>>
Creating Database Web Applications with PHP and ASP
查看>>
ASP.NET 2.0 Demystified
查看>>
Pattern-Oriented Software Architecture, Volume 2, Patterns for Concurrent and Networked Objects
查看>>
Pattern-Oriented Software Architecture, Volume 1: A System of Patterns
查看>>
Database Programming with Visual Basic® .NET and ADO.NET: Tips, Tutorials, and Code
查看>>
ISO 9001: 2000 For Small Businesses
查看>>
Microsoft Visual Studio 2005 Unleashed
查看>>
Windows Server 2003 Security Infrastructures: Core Security Features
查看>>
Configuring ISA Server 2000
查看>>
Microsoft Money 2006 For Dummies
查看>>
Vision with Direction: A Systematic Introduction to Image Processing and Computer Vision
查看>>
Oracle Internals: Tips, Tricks, and Techniques for DBAs
查看>>
Programming Wcf Services
查看>>