标签:返回 bin 退出 节点 rbegin 结果 range ott while
问题:
给定二叉树,进行层序遍历,从底层向上输出。
Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[15,7],[9,20],[3]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000
解法:BFS,DFS
解法一:BFS
从root向底层遍历二叉树:
queue:每层节点。
stack:保存每层结果。
最后将stack中的结果依次pop到res中,返回。
代码参考:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 vector<vector<int>> levelOrderBottom(TreeNode* root) { 15 queue<TreeNode*> q; 16 vector<vector<int>> res; 17 stack<vector<int>> levelset; 18 if(root) q.push(root); 19 while(!q.empty()) { 20 int sz = q.size(); 21 vector<int> curlevel; 22 for(int i=0; i<sz; i++) { 23 TreeNode* cur = q.front(); 24 q.pop(); 25 curlevel.push_back(cur->val); 26 if(cur->left) q.push(cur->left); 27 if(cur->right) q.push(cur->right); 28 } 29 if(!curlevel.empty()) levelset.push(curlevel); 30 } 31 while(!levelset.empty()) { 32 res.push_back(levelset.top()); 33 levelset.pop(); 34 } 35 return res; 36 } 37 };
解法二:DFS
深度优先搜索:先遍历到:左下角第一个子节点->从左到右第二个子节点...
在遍历第一个子节点的路途中(res.size一定==当前level),依次遍历第0层,第1层,第2层...第n层,同时创建每一层res[level],即:res.push_back( vector<int>() );
同时把路过的各层第一个节点加入各层res中:res.[level].push_back(root->val);
最后返回反向遍历的res:vector<vector<int>> (res.rbegin(), res.rend());
代码参考:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 vector<vector<int>> res; 15 void dfs(TreeNode* root, int level) { 16 if(!root) return; 17 if(level==res.size()) res.push_back(vector<int>());//for every new level: initialize res 18 res[level].push_back(root->val); 19 dfs(root->left, level+1); 20 dfs(root->right,level+1); 21 return; 22 } 23 vector<vector<int>> levelOrderBottom(TreeNode* root) { 24 dfs(root, 0); 25 return vector<vector<int>>(res.rbegin(), res.rend()); 26 } 27 };
107. Binary Tree Level Order Traversal II
标签:返回 bin 退出 节点 rbegin 结果 range ott while
原文地址:https://www.cnblogs.com/habibah-chang/p/14445986.html