Binary Tree Zigzag Level Order Traversal
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
解题思路:
可以先获得二叉树的高度,分配vector的大小,然后通过先序遍历,插入对应的层中。根据深度的奇偶来选择插在前面还是插在后面。
/** * 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) { int h = getHeight(root); vector<vector<int>> result(h, vector<int>()); preOrder(root, 0, result); return result; } void preOrder(TreeNode* root, int h, vector<vector<int>>& result){ if(root==NULL){ return; } if(h%2==0){ result[h].push_back(root->val); }else{ result[h].insert(result[h].begin(), root->val); } preOrder(root->left, h+1, result); preOrder(root->right, h+1, result); } int getHeight(TreeNode* root){ if(root == NULL){ return 0; } return 1 + max(getHeight(root->left), getHeight(root->right)); } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
[LeetCode] Binary Tree Zigzag Level Order Traversal
原文地址:http://blog.csdn.net/kangrydotnet/article/details/47337645