103 Binary Tree Zigzag Level Order Traversal 二叉樹的鋸齒形層次遍歷
阿新 • • 發佈:2018-04-04
bsp size light emp == push 鋸齒形 .com null
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回鋸齒形層次遍歷如下:
[
[3],
[20,9],
[15,7]
]
詳見:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/
/** * 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>> res; if(!root) { return res; } queue<TreeNode*> que; que.push(root); int i=1; bool flag=true; vector<int> out; while(!que.empty()) { root=que.front(); que.pop(); --i; if(root->left) { que.push(root->left); } if(root->right) { que.push(root->right); } if(flag) { out.push_back(root->val); } else { out.insert(out.begin(),root->val); } if(i==0) { i=que.size(); res.push_back(out); flag=!flag; out.clear(); } } return res; } };
103 Binary Tree Zigzag Level Order Traversal 二叉樹的鋸齒形層次遍歷