LeetCode No.103 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,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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值