本文主要是介绍Leetcode 103 Binary Tree Zigzag Level Order Traversal(BFS),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目连接:Leetcode 103 Binary Tree Zigzag Level Order Traversal
解题思路:与Leetcode 102 一样,使用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>> zigzagLevelOrder(TreeNode* root) {vector<vector<int>> ans;if (root == NULL) return ans;queue<TreeNode*> que;que.push(root);int f = 0;while (!que.empty()) {vector<int> cur;int n = que.size();while (n--) {TreeNode* t = que.front();que.pop();cur.push_back(t->val);if (t->left != NULL) que.push(t->left);if (t->right != NULL) que.push(t->right);}if (f) reverse(cur.begin(), cur.end());f ^= 1;ans.push_back(cur);}return ans;}
};
这篇关于Leetcode 103 Binary Tree Zigzag Level Order Traversal(BFS)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!