solution.md 1.4 KB
Newer Older
ToTensor's avatar
ToTensor 已提交
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
# 二叉树的锯齿形层序遍历

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

<p>例如:<br />
给定二叉树 <code>[3,9,20,null,null,15,7]</code>,</p>

<pre>
    3
   / \
  9  20
    /  \
   15   7
</pre>

<p>返回锯齿形层序遍历如下:</p>

<pre>
[
  [3],
  [20,9],
  [15,7]
]
</pre>


## template

```python
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        import collections

        if not root:
            return []

        res, q = [], collections.deque()
        flag = False
        q.append(root)

        while q:
            temp = []
            flag = not flag
            for _ in range(len(q)):
                node = q.popleft()

                if flag:
                    temp.append(node.val)

                else:
                    temp.insert(0, node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            res.append(temp)

        return res
```

## 答案

```python

```

## 选项

### A

```python

```

### B

```python

```

### C

```python

```