LeetCode No.103 Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:微信商城 源码下载 编辑:程序博客网 时间:2024/05/21 20:54

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]]

====================================================================================
题目链接:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
题目大意:求二叉树的层次遍历,假设root为第0层,返回结果中奇数层需要翻转。
思路:因为我们需要从左往右保存二叉树每个层的信息,要保证顺序的准确性,使用stack栈操作会打乱顺序,所以这里我们需要运用queue队列操作,存储的结构为pair <TreeNode*,int>,分别对应二叉树节点以及该节点对应的层。然后进行层次遍历,存储结果。注意最后还需要将奇数层进行翻转。
附上代码:

/** * 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 ;        vector <int> ttt ;        //ans.push_back ( ttt ) ;        if ( root == NULL )            return ans ;        queue < pair <TreeNode*,int> > q ;                while ( ! q.empty() )            q.pop() ;        q.push ( make_pair ( root , 0 ) ) ;        while ( !q.empty() )        {            pair <TreeNode*,int> node = q.front() ;            q.pop() ;            TreeNode* temp = node.first ;            int index = node.second ;            if ( ans.size() <= index )                ans.push_back ( ttt ) ;            ans[index].push_back ( temp -> val ) ;            if ( temp -> left )                q.push ( make_pair ( temp -> left , index + 1 ) ) ;            if ( temp -> right )                q.push ( make_pair ( temp -> right , index + 1 ) ) ;        }        for ( int i = 0 ; i < ans.size() ; i ++ )        {            if ( i % 2 )                reverse ( ans[i].begin() , ans[i].end() ) ;        }        return ans ;    }};


0 0