题目:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
提示:
此题要求逐行输出二叉树的节点数值,这里提供两种解法,第一种基于BFS,第二种基于DFS。
代码:
BFS:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if (!root) return res; queue<TreeNode*> q; vector<int> v; q.push(root); q.push(NULL); TreeNode *node; while(!q.empty()) { node = q.front(); q.pop(); if (node == NULL) { res.push_back(v); v.clear(); if (q.size()) q.push(NULL); } else { v.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } } return res; } };
DFS:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { search(root, 0); return res; } private: void search(TreeNode* node, int depth) { if (!node) return; if (res.size() == depth) { res.push_back(vector<int>()); } res[depth].push_back(node->val); search(node->left, depth + 1); search(node->right, depth + 1); } vector<vector<int>> res; };