二叉树的层序遍历
思路一:利用队列,将每一层节点放入队列,各层节点之间加入NULL隔开。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int> > levelOrderBottom(TreeNode *root) { 13 vector<vector<int> > levelOrderVec; 14 if (root == NULL) 15 return levelOrderVec; 16 queue<TreeNode *> treeQueue; 17 treeQueue.push(root); 18 treeQueue.push(NULL); 19 vector<int> level; 20 while (!treeQueue.empty()) 21 { 22 TreeNode *tmp = treeQueue.front(); 23 treeQueue.pop(); 24 if (tmp != NULL) 25 { 26 level.push_back(tmp->val); 27 if (tmp->left) 28 treeQueue.push(tmp->left); 29 if (tmp->right) 30 treeQueue.push(tmp->right); 31 } 32 else 33 { 34 if (level.size() != 0) 35 { 36 levelOrderVec.push_back(level); 37 treeQueue.push(NULL); 38 } 39 level.clear(); 40 } 41 } 42 43 reverse(levelOrderVec.begin(), levelOrderVec.end()); 44 45 return levelOrderVec; 46 } 47 };
思路二:深度优先搜索
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int> > levelOrderBottom(TreeNode *root) { 13 DFS(root, 0); 14 return vector<vector<int> > (res.rbegin(), res.rend()); 15 } 16 17 void DFS(TreeNode *root, int level) 18 { 19 if (root == NULL) return; 20 // 当前level不存在 21 // 新建一个 22 if (level == res.size()) 23 { 24 res.push_back(vector<int>()); 25 } 26 27 res[level].push_back(root->val); 28 DFS(root->left, level+1); 29 DFS(root->right, level+1); 30 } 31 32 private: 33 vector<vector<int> > res; 34 };