Q:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
T:简单而言就是层序遍历,使用队列。
A:

    vector<int> PrintFromTopToBottom(TreeNode* root) {
        queue<TreeNode*> q;
        vector<int> array;
        if(root == nullptr)
            return array;
        q.push(root);
        while(!q.empty()){
            TreeNode* node = q.front();
            if(node->left)
                q.push(node->left);
            if(node->right)
                q.push(node->right);
            array.push_back(node->val);
            q.pop();
        }
        return array;
    }

相关文章:

  • 2021-09-19
  • 2022-01-23
  • 2021-09-23
  • 2022-02-09
  • 2021-10-17
  • 2022-12-23
  • 2021-10-18
猜你喜欢
  • 2022-02-27
  • 2022-01-19
  • 2022-12-23
  • 2021-07-20
  • 2021-07-05
  • 2021-09-21
  • 2022-01-07
相关资源
相似解决方案