• [leetcode-107-Binary Tree Level Order Traversal II]


    Given a binary tree, return the bottom-up level order traversal of its nodes' values.
    (ie, from left to right, level by level from leaf to root).
    For example:
    Given binary tree [3,9,20,null,null,15,7],
    3
    /
    9 20
    /
    15 7
    return its bottom-up level order traversal as:
    [
    [15,7],
    [9,20],
    [3]
    ]

    思路:

    这个跟leetcode-102-Binary Tree Level Order Traversal 其实差不多的。

    唯一不同的是在每一层遍历完之后,得到本层的数值,插入到最终result数组里的时候从头插入,即可实现倒序。

        vector<vector<int>> levelOrderBottom(TreeNode* root)
        {
            queue<TreeNode*>que;
            vector<vector<int>>result;
            if (root == NULL)return result;
            que.push(root);
    
            while (!que.empty())
            {
                int size = que.size();
                vector<int> temp;
                for (int i = 0; i < size; i++)
                {
                    TreeNode* node = que.front();
                    que.pop();
                    temp.push_back(node->val);
                    if (node->left != NULL)que.push(node->left);
                    if (node->right != NULL)que.push(node->right);
                }            
                result.insert(result.begin(), temp);//从头部插入即可实现倒序
            }
            return result;
        }
  • 相关阅读:
    PHP入门
    requests中text,content,json之间的区别
    有关pip报错的问题

    pycharm操作
    python selenium 相关操作
    python tkinter菜单
    初识Go
    Python _easygui详细版
    easygui _1
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6642036.html
Copyright © 2020-2023  润新知