标签:
从上往下打印二叉树的每一个节点,同一层的节点按照从左至右的顺序打印,二叉树节点的数据结构如下:
1 struct TreeNode { 2 int val; 3 struct TreeNode *left; 4 struct TreeNode *right; 5 TreeNode(int x) : 6 val(x), left(NULL), right(NULL) { 7 } 8 };
二叉树的广度优先遍历,用一个队列就可以解决:
1 vector<int> PrintFromTopToBottom(TreeNode *root) { 2 queue<TreeNode*> nodes; 3 vector<int> outputValue; 4 if(root == NULL) 5 return outputValue; 6 int index = 0; 7 nodes.push_back(root); 8 while(!nodes.empty()){ 9 TreeNode* node; 10 node = nodes.front(); 11 outputValue.push_back(node->val); 12 if(node->left != NULL) 13 nodes.push(node->left); 14 if(node->right != NULL) 15 nodes.push(node->right); 16 } 17 return outputValue; 18 }
标签:
原文地址:http://www.cnblogs.com/yangrenzhi/p/5787035.html