給定一顆二叉搜索樹,請找出其中的第k大的結點


 
         

//概念問題 二叉搜索樹 要么為空 如果左節點不為空 那么根節點的值大於左節點 如果右節點不為空 那么右節點的值大根節點的值
//對二叉排序樹的中序遍歷 是一個遞增的序列

 

1
/* 2 public class TreeNode { 3 int val = 0; 4 TreeNode left = null; 5 TreeNode right = null; 6 7 public TreeNode(int val) { 8 this.val = val; 9 10 } 11 12 } 13 */ 14 15 import java.util.ArrayList; 16 public class Solution { 17 ArrayList<TreeNode>list=new ArrayList<TreeNode>(); 18 TreeNode KthNode(TreeNode pRoot, int k) 19 { 20 if(k<1) return null; //注意程序的魯棒性 就是對不同的k值的響應 21 inorder(pRoot); 22 if(k>list.size())return null; 23 TreeNode node=list.get(k-1); 24 return node; 25 26 } 27 public void inorder(TreeNode pRoot){ 28 if(pRoot==null)return; 29 inorder(pRoot.left); 30 list.add(pRoot); 31 inorder(pRoot.right); 32 33 } 34 35 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM