首页 > 其他 > 详细

leetcode 103. 二叉树的锯齿形层次遍历(Binary Tree Zigzag Level Order Traversal)

时间:2019-04-28 15:09:23      阅读:103      评论:0      收藏:0      [点我收藏+]

题目描述:

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

返回锯齿形层次遍历如下:

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

解法:

/**
 * 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>> res;
        vector<TreeNode*> cur, nxt;
        bool forward = true;
        if(root){
            cur.push_back(root);
            vector<int> lst;
            while(!cur.empty()){
                lst.clear();
                nxt.clear();
                for(TreeNode* node : cur){
                    lst.push_back(node->val);
                    if(node->left){
                        nxt.push_back(node->left);
                    }
                    if(node->right){
                        nxt.push_back(node->right);
                    }
                }
                if(forward == false){
                    forward = true;
                    lst = vector<int>(lst.rbegin(), lst.rend());
                }else{
                    forward = false;
                }
                res.push_back(lst);
                cur = nxt;
            }
        }
        return res;
    }
};

leetcode 103. 二叉树的锯齿形层次遍历(Binary Tree Zigzag Level Order Traversal)

原文:https://www.cnblogs.com/zhanzq/p/10783838.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!