标签:order turn traversal div null binary 水平 between tree
算法描述:
Given a binary tree, return the zigzag level order traversal of its nodes‘ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
解题思路:与水平访问一样,用队列实现。区别在于加入一个判断,在偶数行反向插入数值就行。
vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> results; helper(root, results,0); return results; } void helper(TreeNode* root, vector<vector<int>>& results, int level){ if(root ==nullptr) return; if(results.size() <= level){ vector<int> temp; results.push_back(temp); } if(level%2==0){ results[level].push_back(root->val); }else{ results[level].insert(results[level].begin(),root->val); } helper(root->left,results,level+1); helper(root->right,results,level+1); }
LeetCode-103-Binary Tree Zigzag Level Order Traversal
标签:order turn traversal div null binary 水平 between tree
原文地址:https://www.cnblogs.com/nobodywang/p/10349580.html