[Sword refers to Offer learning] [interview question 63: k node of the Binary Search Tree], sword refers to offer
Question: Given a binary search tree, locate the k-th node in the tree.Solutions
If a binary search tree is traversed sequentially, the values of the traversal sequence are sorted progressively. You only need to traverse a binary search tree by using the Middle-order traversal algorithm, and it is easy to find its k-node.
Node Definition
private static class BinaryTreeNode { private int val; private BinaryTreeNode left; private BinaryTreeNode right; public BinaryTreeNode() { } public BinaryTreeNode(int val) { this.val = val; } @Override public String toString() { return val + ""; }}
Code Implementation
Public class Test63 {private static class BinaryTreeNode {private int val; private BinaryTreeNode left; private BinaryTreeNode right; public BinaryTreeNode () {} public BinaryTreeNode (int val) {this. val = val ;}@ Override public String toString () {return val + "" ;}} public static BinaryTreeNode kthNode (BinaryTreeNode root, int k) {if (root = null | k <1) {return null;} int [] tmp = {k }; Return kthNodeCore (root, tmp);} private static BinaryTreeNode kthNodeCore (BinaryTreeNode root, int [] k) {BinaryTreeNode result = null; // search for if (root. left! = Null) {result = kthNodeCore (root. left, k);} // if the left subtree does not find if (result = null) {// indicates that the current root node is the target node if (k [0] = 1) {result = root ;} else {// The current root node is not the node to be found, but it has already been found, so the counter minus one k [0] --;} // if neither the root node nor the right child node of the root node is found, find the right child tree if (result = null & root. right! = Null) {result = kthNodeCore (root. right, k);} return result;} public static void main (String [] args) {BinaryTreeNode n1 = new BinaryTreeNode (1); BinaryTreeNode n2 = new BinaryTreeNode (2 ); binaryTreeNode n3 = new BinaryTreeNode (3); BinaryTreeNode n4 = new BinaryTreeNode (4); BinaryTreeNode n5 = new BinaryTreeNode (5); BinaryTreeNode n6 = new BinaryTreeNode (6 ); binaryTreeNode n7 = new BinaryTreeNo De (7); BinaryTreeNode n8 = new BinaryTreeNode (8); BinaryTreeNode encoding = new BinaryTreeNode (9); n1.left = n2; n1.right = n3; n2.left = n4; n2.right = n5; n3.left = n6; n3.right = n7; n4.left = n8; n4.right = bytes; print (n1); System. out. println (); for (int I = 0; I <= 10; I ++) {System. out. printf (kthNode (n1, I) + ",") ;}/ *** traverse a tree in ascending order * @ param root */private static void print (BinaryTreeNode root ){ If (root! = Null) {print (root. left); System. out. printf ("%-3d", root. val); print (root. right );}}}
Running result
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/46872313]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.