1. 程式人生 > >LeetCode 103.Binary Tree Zigzag Level Order Traversal (二叉樹的鋸齒形層次遍歷)

LeetCode 103.Binary Tree Zigzag Level Order Traversal (二叉樹的鋸齒形層次遍歷)

題目描述:

給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。

例如:

給定二叉樹 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回鋸齒形層次遍歷如下:

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

AC C++ Solution:

使用一個雙端佇列解決“之”字型遍歷:

/**
 * 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;
        if(!root) return res;
        deque<TreeNode*> deq;
        deq.push_back(root);
        bool ltor=false;     //left to right
        while(!deq.empty()) {
            int sz=deq.size();
            ltor = !ltor ;
            vector<int> row;
            while(sz--) {
                if(ltor) {
                    root = deq.back();  deq.pop_back();
                    row.push_back(root->val);
                    if(root->left) deq.push_front(root->left);
                    if(root->right)  deq.push_front(root->right);
                }
                else {
                    root = deq.front(); deq.pop_front();
                    row.push_back(root->val);
                    if(root->right) deq.push_back(root->right);
                    if(root->left)  deq.push_back(root->left);
                }
            }
            res.push_back(row);
        }
        return res;
    }
};

從左到右遍歷時,從佇列尾取節點,並把子節點按左到右的順序依次加入佇列頭;

從右到左遍歷時,從佇列頭取節點,並把子節點按右到左的順序依次加入佇列尾;