Binary Tree Zigzag Level Order Traversal - LeetCode
阿新 • • 發佈:2019-03-19
奇數 oot 訪問 ack tle tree () 圖片 lee
目錄
- 題目鏈接
- 註意點
- 解法
- 小結
題目鏈接
Binary Tree Zigzag Level Order Traversal - LeetCode
註意點
- 不要訪問空結點
解法
解法一:遞歸,遞歸,在Binary Tree Level Order Traversal - LeetCode的基礎上將奇數層(下標從0開始)結果逆序即可。
/** * 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: typedef vector<vector<int>> v; typedef TreeNode* node; void bfs(int level,node n,v& ret) { if(ret.size() == level) ret.push_back({}); ret[level].push_back(n->val); if(n->left) bfs(level+1,n->left,ret); if(n->right) bfs(level+1,n->right,ret); } vector<vector<int>> zigzagLevelOrder(TreeNode* root) { v ret; if(!root) return ret; bfs(0,root,ret); int i = 0,n = ret.size(); for(i = 0;i < n;i++) { if(i%2 == 1) reverse(ret[i].begin(),ret[i].end()); } return ret; } };
解法二:非遞歸,同樣在Binary Tree Level Order Traversal - LeetCode的基礎上訪問到奇數層時結果逆序即可。
/** * 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: typedef vector<vector<int>> v; typedef TreeNode* node; vector<vector<int>> zigzagLevelOrder(TreeNode* root) { v ret; if(!root) return ret; int level = 0; queue<node> q; q.push(root); while(!q.empty()) { vector<int> aLevel; for(int i = q.size();i > 0;--i) { node n = q.front(); q.pop(); aLevel.push_back(n->val); if(n->left) q.push(n->left); if(n->right) q.push(n->right); } if(level%2 == 1) reverse(aLevel.begin(),aLevel.end()); ret.push_back(aLevel); level++; } return ret; } };
小結
Binary Tree Zigzag Level Order Traversal - LeetCode