题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
题解一:DFS 借助栈实现
1 // 中序非递归 2 public static TreeNode KthNode02(TreeNode pRoot, int k) { 3 Stack<TreeNode> stack = new Stack<>(); 4 if(pRoot==null||k<=0){ 5 return null; 6 } 7 int count=0; 8 while(pRoot!=null||!stack.isEmpty()){ 9 while(pRoot!=null){ 10 stack.push(pRoot); 11 pRoot=pRoot.left; 12 } 13 pRoot = stack.pop(); 14 count++; 15 if(count==k){ 16 return pRoot; 17 } 18 pRoot=pRoot.right; 19 } 20 return null; 21 }
1 //中序遍历二叉搜索树后正好是从小到大的顺序,直接返回第k-1个即可 2 private static ArrayList<TreeNode> treeNode=new ArrayList<TreeNode>(); 3 public static TreeNode KthNode01(TreeNode pRoot, int k) { 4 //中序遍历 5 InOrder(pRoot); 6 if(treeNode.size()<1||k<1||k>treeNode.size()) { 7 return null; 8 } 9 return treeNode.get(k-1); 10 } 11 public static void InOrder(TreeNode node) { 12 if(node!=null) 13 { 14 InOrder(node.left); 15 treeNode.add(node); 16 InOrder(node.right); 17 } 18 }
1 public static int index = 0; 2 public static TreeNode KthNode(TreeNode pRoot, int k) { 3 //中序遍历寻找第k个 4 if(pRoot != null){ 5 TreeNode node = KthNode(pRoot.left,k); 6 if(node != null) { 7 return node; 8 } 9 index ++; 10 if(index == k) { 11 return pRoot; 12 } 13 node = KthNode(pRoot.right,k); 14 if(node != null) { 15 return node; 16 } 17 } 18 return null; 19 }
初始化树:
public static class TreeNode{ int val=0; TreeNode left=null; TreeNode right=null; public TreeNode(int val){ this.val=val; } } private static List<TreeNode> nodeList = null; public static TreeNode createBinTree(int[] array) { nodeList=new LinkedList<TreeNode>(); // 将一个数组的值依次转换为TreeNode节点 for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) { nodeList.add(new TreeNode(array[nodeIndex])); } // 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树 for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) { // 左孩子 nodeList.get(parentIndex).left = nodeList .get(parentIndex * 2 + 1); // 右孩子 nodeList.get(parentIndex).right = nodeList .get(parentIndex * 2 + 2); } // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理 int lastParentIndex = array.length / 2 - 1; // 左孩子 nodeList.get(lastParentIndex).left = nodeList .get(lastParentIndex * 2 + 1); // 右孩子,如果数组的长度为奇数才建立右孩子 if (array.length % 2 == 1) { nodeList.get(lastParentIndex).right = nodeList .get(lastParentIndex * 2 + 2); } return nodeList.get(0); }
测试:
1 public static void main(String[] args) { 2 int[] arr= {8,6,10,5,7,9,11}; 3 int k=2; 4 TreeNode root = createBinTree(arr); 5 TreeNode node = KthNode02(root, k); 6 System.out.println(node.val); 7 } 8 输出:6