标签:== 遍历 pos 一个 ++ script root length 需要
创建> 需要给定一个root的key,所有小于这个key的放到左边,大于key的放到右边, 比如vector<int> tree = {5,2,7,1,9,3,8},最后的树:
5 / 2 7 /\ / 1 3 8 9
实现:
TreeNode* AddNode(int key, int direction, TreeNode* root) { if(direction == 0)//左孩子 { if(root->leftChild == NULL){//找到对应的叶节点插入 root->leftChild = new binaryTreeNode<T>(key); } else{ root->leftChild = AddNode(key, direction, root->leftChild); } } else//右孩子 { if (root->rightChild == NULL) {//找到相应的叶节点插入 root->rightChild = new binaryTreeNode<T>(key); } else{ root->rightChild = AddNode(key, direction, 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; }
标签:== 遍历 pos 一个 ++ script root length 需要
原文地址:https://www.cnblogs.com/feliz/p/11272751.html