题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ //就是二叉树的层次遍历,如果要求从下往上打印的话,用reverse函数颠倒一下。 class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { vector<int> ans; TreeNode* t; if(root==NULL) return ans; queue<TreeNode*> p; p.push(root); while(!p.empty()) { t=p.front(); ans.push_back(t->val); if(t->left!=NULL) p.push(t->left); if(t->right!=NULL) p.push(t->right); p.pop(); } return ans; } };
|
近期评论