71 二叉树的锯齿形层次遍历 Lintcode---二叉树的锯齿形层次遍历

原题网址:https://www.lintcode.com/problem/binary-tree-zigzag-level-order-traversal/description

描述

给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行) 

您在真实的面试中是否遇到过这个题?  

样例

给出一棵二叉树 {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

返回其锯齿形的层次遍历为:

[
  [3],
  [20,9],
  [15,7]
]

标签
队列
二叉树
二叉树遍历
Breadth-first Search(BFS)
 
 
思路:二叉树的层次遍历,广度优先搜索。因为是分层遍历,所以可设置两个队列。
1.在遍历当前层节点队列之前,将此队列保存下来。然后遍历节点的数值,将数组push到result中;
2.更新当前层队列:遍历当前层队列副本,访问节点的left与right,如果存在,将其push到当前层队列中;
3.重复以上步骤直到当前层队列为空,此时层次遍历完毕。
4.题目要求输出结果锯齿形,所以将二叉树偶数层翻转,即下标从1开始遍历result,将索引为奇数的一维数组翻转。
 
AC代码:
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A Tree
     * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
     */
    vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
        // write your code here
    vector<vector<int>> result;
    if (root==NULL)
    {
        return result;
    }

    queue<TreeNode *> tmp;
    queue<TreeNode *> temp;
    tmp.push(root);

    while(!tmp.empty())
    {
        temp=tmp;//保存当前层队列,以便后续创建下一层队列;
        vector<int> vec;
        while(!tmp.empty())//遍历当前层;
        {
            vec.push_back(tmp.front()->val);
            tmp.pop();    
        }
        result.push_back(vec);

        while(!temp.empty())//将下一层保存在tmp中;
        {
            TreeNode * tNode=temp.front();
            temp.pop();
            if (tNode->left)
            {
                tmp.push(tNode->left);
            }
            if (tNode->right)
            {
                tmp.push(tNode->right);
            }
        }
    }

    //将偶数层翻转;
    for (int j=1;j<(int)result.size();j+=2)
    {
        reverse(result[j].begin(),result[j].end());
    }

    return result;
    }
};
其他思路:Lintcode---二叉树的锯齿形层次遍历   膜拜大神
 
 

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9263676.html