Thursday, July 23, 2015

LintCode (71) Binary Tree Zigzag

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).
Have you met this question in a real interview? 
Yes
Example
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]
]

反正反过来覆过去都是这几招。。。BFS!!!,中间随便做点手脚。。。


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 

class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: A list of lists of integer include 
     *          the zigzag level order traversal of its nodes' values 
     */
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
        // write your code here
        vector< vector<int>> result;
        if (!root)
            return result;
        queue<TreeNode*> q;
        q.push(root);
        bool reverse=false;
        while(!q.empty()){
            int size=q.size();
            vector<int> solution;
            for (int i=0; i<size; i++){
                TreeNode* cur= q.front();
                q.pop();
                if (!reverse){
                    solution.push_back(cur->val);
                } else{
                    solution.insert(solution.begin(), cur->val);
                }
                if (cur->left)
                    q.push(cur->left);
                if (cur->right)
                    q.push(cur->right);
            }
            result.push_back(solution);
            reverse=!reverse;
        }
        return result;
    }
};

No comments:

Post a Comment