标签:deque name print offer tac stack using mes 题目
/* 题目: 按层自上向下打印二叉树。 */ /* 思路: 使用队列,将节点压入队列中,再弹出来,压入其左右子节点,循环,直到栈为空。 */ #include<iostream> #include<string.h> #include<algorithm> #include<cmath> #include<stdio.h> #include<vector> #include<stack> #include<queue> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; vector<int> PrintFromTopToBottom(TreeNode* root){ vector<int> sequence; if(root == nullptr) return sequence; deque<TreeNode*> myQueue; myQueue.push_back(root); TreeNode *temp; while(!myQueue.empty()){ temp = myQueue.front(); myQueue.pop_front(); sequence.push_back(temp->val); if(temp->left != nullptr){ myQueue.push_back(temp->left); } if(temp->right != nullptr){ myQueue.push_back(temp->right); } } return sequence; } int main(){ TreeNode* node1 = new TreeNode(1); TreeNode* node2 = new TreeNode(2); TreeNode* node3 = new TreeNode(3); node1->left = node2; node2->right = node3; vector<int> m = PrintFromTopToBottom(node1); for(int i = 0; i < m.size(); i++){ cout<<m[i]<<" "; } }
标签:deque name print offer tac stack using mes 题目
原文地址:https://www.cnblogs.com/buaaZhhx/p/11938603.html