从上到下打印二叉树 III

in 知识共享 with 0 comment

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

提示:

节点总数 <= 1000

本人提交代码

/**
 * 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>> results;
        if ( !root )
            return results;

        deque<TreeNode*> nodes;
        nodes.push_back( root );
        
        bool l2r = true;
        while ( !nodes.empty() )
        {
            vector<int> row;
            int size = nodes.size();
            TreeNode* node = node;
            while ( size-- > 0 )
            {
                if ( l2r )
                {
                    node = nodes.front();
                    nodes.pop_front();
                    if ( node->left )
                        nodes.push_back( node->left );
                    if ( node->right )
                        nodes.push_back( node->right );   
                }
                else
                {
                    node = nodes.back();
                    nodes.pop_back();
                    if ( node->right )
                        nodes.push_front( node->right );
                    if ( node->left )
                        nodes.push_front( node->left );
                }
                row.push_back( node->val );
            }
            results.push_back( row );
            l2r = !l2r;
        }
        return results;
    }
};
Responses