利用二叉查找樹中序遍歷有序的特色。java
private TreeNode ret; private int cnt = 0; public TreeNode KthNode(TreeNode pRoot, int k) { inOrder(pRoot, k); return ret; } private void inOrder(TreeNode root, int k) { if (root == null || cnt >= k) return; inOrder(root.left, k); cnt++; if (cnt == k) ret = root; inOrder(root.right, 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; } }