Max-Heapify A Binary Tree

后端 未结 4 485
半阙折子戏
半阙折子戏 2020-12-31 11:43

This is one of the interview questions I recently came across.

Given the root address of a complete or almost complete binary tree, we have to write a function to c

4条回答
  •  有刺的猬
    2020-12-31 11:49

    I think you can get one work simply by revising postOrderTraverse. This is O(n)

    void Heapify_Min(TreeNode* node)
    {
      if(! = node) return;
       Heapify_Min(node->left);
       Heapify_Min(node->right);
       TreeNode* largest = node;
       if(node->left && node->left->val > node->val)
          largest = node->left;
       if(node->right && node->right->val > node->val)
          largest = node->right;
    
      if(largest != node)
      {
        swap(node, largest)
      }
    }
    
    void swap(TreeNode* n1, TreeNode* n2)
    {
        TreeNode* temp = n1->left;
        n1->left = n2->left;
        n2->left =temp;
    
        temp = n1->right;
        n1->right = n2->right;
        n2->right = temp;
    }
    
    }
    

提交回复
热议问题