/* 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 pRoot, int k) { //遞歸終止條件 if(pRoot==null){ return null; } //左子樹中找符合要求的節點 TreeNode node=KthNode(pRoot.left,k); if(node!=null) return node; //根 if(++count==k) return pRoot; //右子樹中找符合要求的節點 node=KthNode(pRoot.right,k); if(node!=null) return node; return null; } }
二叉搜索樹按照中序遍歷的順序打印出來正好就是排序好的順序。
按照中序遍歷順序找到第k個結點便可。