剑指offer - 从上到下打印二叉树 III

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]

解法一:给层标号,符合条件的就反向输出(Python)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        res = []
        if not root: return res
        qu = [root]
        j = -1
        while qu:
            j += 1
            n = len(qu)
            tmp = []
            for i in range(n):
                node = qu.pop(0)
                tmp.append(node.val)
                if  node.left: qu.append(node.left)
                if node.right: qu.append(node.right)
            if j % 2:
                tmp.reverse()
            res.append(tmp)
        return res

解法二:双端队列(C++)

奇数层正常队列,偶数层反向队列

/**
 * 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>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(!root) return res;
        bool flag = true;
        deque<TreeNode*> q;
        q.push_back(root);
        while(!q.empty())
        {
            int n = q.size();
            vector<int> tmp;
            TreeNode* node;
            while(n)
            {
                if(flag)
                {
                    node = q.front();
                    q.pop_front();
                    if(node->left) q.push_back(node->left);
                    if(node->right) q.push_back(node->right);
                }
                else 
                {
                    node = q.back();
                    q.pop_back();
                    if(node->right) q.push_front(node->right);
                    if(node->left) q.push_front(node->left);
                
                tmp.push_back(node->val);
                n--;
            }
            flag = !flag;
            res.push_back(tmp);
        }
        return res;
    }
};

你可能感兴趣的:(题解)