题目:给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {3,9,20,#,#,15,7}
:
3
/ 9 20
/ 15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
挑战
挑战1:只使用一个队列去实现它
挑战2:用DFS算法来做
解:用队列
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /* * @param root: A Tree * @return: Level order a list of lists of integer */ vector<vector<int>> levelOrder(TreeNode * root) { vector<vector<int>> res; if(root==NULL) return res; queue<TreeNode*> q; q.push(root); int sz; while(!q.empty()) { vector<int> temp; sz=q.size(); while(sz--) { TreeNode *fNode=q.front(); temp.push_back(fNode->val); q.pop(); if(fNode->left!=NULL) { q.push(fNode->left); } if(fNode->right!=NULL) { q.push(fNode->right); } } res.push_back(temp); } return res; } };