zoukankan      html  css  js  c++  java
  • 剑指offer-二叉搜索树的第k个结点

    题目描述

    给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。
     
    中序遍历二叉搜索树,找到第k个结点,除了使用递归,还可以使用栈实现非递归写法
     1 public class Solution {//树 my
     2     int index = 0;
     3     TreeNode KthNode(TreeNode pRoot, int k)
     4     {
     5         if(pRoot==null){
     6             return null;
     7         }
     8         return getK(pRoot,k);
     9     }
    10     TreeNode getK(TreeNode root,int k){
    11         if(root==null){
    12             return null;
    13         }
    14         TreeNode left = getK(root.left,k);
    15         if(left!=null){
    16             return left;
    17         }
    18         index++;
    19         if(index==k){
    20             return root;
    21         }
    22         TreeNode right = getK(root.right,k);
    23         if(right!=null){
    24             return right;
    25         }
    26         return null;
    27     }
    28 }

    代码可简化为

     1 public class Solution {
     2     int index = 0;
     3     TreeNode KthNode(TreeNode pRoot, int k)
     4     {
     5         if(pRoot!=null){
     6             TreeNode left = KthNode(pRoot.left,k);
     7             if(left!=null){
     8                 return left;
     9             }
    10             index++;
    11             if(index==k){
    12                 return pRoot;
    13             }
    14             TreeNode right = KthNode(pRoot.right,k);
    15             if(right!=null){
    16                 return right;
    17             }
    18         }
    19         return null;
    20     }
    21 }
  • 相关阅读:
    近期学习情况
    java连接数据库的两种方法总结
    近两个星期学习成果
    云笔记第一阶段总结
    圆面积
    C++计算器项目的初始部分
    C++视频课程
    A+B Format
    大一下学期的自我目标
    Kohana的请求流
  • 原文地址:https://www.cnblogs.com/zhacai/p/10686447.html
Copyright © 2011-2022 走看看