leetcode103

问题描述:
其实就是给了一个二叉搜索树,然后按照龙摆尾的方式输出出来,在层序遍历的方式进行改变,其实就增加了两行代码,一个是flag标志位,一个是按照flag的true与false来更改存储顺序。

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]
]



C++
1
/**
2
 * Definition for a binary tree node.
3
 * struct TreeNode {
4
 *     int val;
5
 *     TreeNode *left;
6
 *     TreeNode *right;
7
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8
 * };
9
 */
10
class Solution {
11
public:
12
vector<vector<int> > zigzagLevelOrder(TreeNode* root)
13
{
14
    if(root==NULL)
15
        return vector<vector<int> > ();
16
    vector<vector<int>>res;
17
    //用队列存储这个层的结点
18
    queue<TreeNode*>queue;
19
    queue.push(root);
20
    //作为奇偶行的判断标志
21
    bool flag=true;
22
    while(!queue.empty())
23
    {
24
        int size=queue.size();//该层有多少结点
25
        vector<int>row(size);
26
        for(int i=0;i<size;i++)
27
        {
28
            TreeNode*tempnode=queue.front();
29
            queue.pop();
30
            if(tempnode->left)
31
            {
32
                queue.push(tempnode->left);
33
            }
34
            if(tempnode->right)
35
            {
36
                queue.push(tempnode->right);
37
            }
38
            //把该结点按照龙摆尾的条件存储
39
            //方法就是在下表做文章,从最高位开始存储,然后下一次再从低位开始
40
            int idex=(flag)?i:size-1-i;
41
            row[idex]=tempnode->val;
42
        }
43
        //该层已经能够循环完了  接下来就是下一蹭了
44
        //把改行数据存起来,千万不要忘记更改flag
45
        flag=!flag;
46
        res.push_back(row);
47
        
48
    }
49
    return res;
50
}
51
};
52
 /*   if (root == NULL) {
53
        return vector<vector<int> > ();
54
    }
55
    vector<vector<int> > result;
56
57
    queue<TreeNode*> nodesQueue;
58
    nodesQueue.push(root);
59
    bool leftToRight = true;
60
61
    while ( !nodesQueue.empty()) {
62
        int size = nodesQueue.size();
63
        vector<int> row(size);
64
        for (int i = 0; i < size; i++) {
65
            TreeNode* node = nodesQueue.front();
66
            nodesQueue.pop();
67
68
            // find position to fill node's value
69
            int index = (leftToRight) ? i : (size - 1 - i);
70
71
            row[index] = node->val;
72
            if (node->left) {
73
                nodesQueue.push(node->left);
74
            }
75
            if (node->right) {
76
                nodesQueue.push(node->right);
77
            }
78
        }
79
        // after this level
80
        leftToRight = !leftToRight;
81
        result.push_back(row);
82
    }
83
    return result;
84
}*/


猜你喜欢

转载自blog.csdn.net/qq_40086556/article/details/80912303