二叉搜索树的第k个结点

这里写图片描述

 import java.util.*;
 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 pRoot, int k)
    {
         if(pRoot==null||k<=0)
         {
             return null;
         }
         if(pRoot!=null)
         {
             TreeNode temp=KthNode(pRoot.left,k);
             if(temp!=null)
               return temp;
             if(++count==k)
               return pRoot;
             temp=KthNode(pRoot.right,k);
             if(temp!=null)
               return temp;
         }
         return null;
    }

    //解法二:需要额外的空间
    TreeNode KthNode2(TreeNode pRoot, int k)
    {
        if(pRoot==null||k<=0)
           return null;
       ArrayList<Integer>arr=new ArrayList<>();
       inSearch(pRoot,arr);
       if(k>arr.size())
          return null;
       TreeNode  node=new TreeNode(arr.get(k-1));
       return node;
    }

    //二叉树的中序遍历
    public void inSearch(TreeNode root,ArrayList<Integer>arr)
    {
          if(root!=null)
          {
             inSearch(root.left,arr);
             //System.out.print(root.val);
             arr.add(root.val);
             inSearch(root.right,arr);
          }

    }
    public static void main(String[]args){

         //System.out.println("Hello");
           TreeNode root=new TreeNode(5);
           root.left=new TreeNode(3);
           root.right=new TreeNode(7);
           root.left.left=new TreeNode(2);
           root.left.right=new TreeNode(4);
           root.right.left=new TreeNode(6);
           root.right.right=new TreeNode(8);
           Solution s=new Solution();
           TreeNode node=s.KthNode(root,3);
           System.out.println(node.val);

    }


}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值