Create> needs of a given key of a root, less than all of the key into the left, into the right greater than key, such as vector <int> tree = {5,2,7,1,9,3,8}, and finally tree:
5 / \ 2 7 /\ /\ 1 3 8 9
achieve:
* AddNode TreeNode (int Key, int direction, TreeNode * root) { IF (direction == 0) // Left child { IF (root-> leftChild == NULL) {// find the corresponding leaf node is inserted root-> leftChild new new binaryTreeNode = <T> (Key); } the else { directory root-> = leftChild the AddNode (Key, direction, directory root-> leftChild); } } the else // right child { IF (directory root-> rightChild == NULL) {/ / find the corresponding leaf node into directory root-> rightChild new new binaryTreeNode = <T> (Key); } the else { directory root-> = rightChild the AddNode (Key, direction, directory root-> rightChild); } } return root; } //vector[0]作为root TreeNode* createTree(vector<int>& tree){ int nodes = tree.length(); int pos = 0; if(nodes<1) return NULL; TreeNode* root = new TreeNode(tree[pos++]); while(pos < nodes){ if(tree[pos]<tree[0]) root->left = AddNode(tree[pos++], 0, root); else root->right = AddNode(tree[pos++], 1, root); } return root; }