码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的创建、遍历、删除、求高度

时间:2019-07-30 22:09:32      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:==   遍历   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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!