• [Leetcode] Binary Tree Level Order Traversal II


    Binary Tree Level Order Traversal II 题解

    题目来源:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/


    Description

    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).

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

    Solution

    
    class Solution {
    public:
        vector<vector<int> > levelOrderBottom(TreeNode* root) {
            vector<vector<int> > res;
            if (root == NULL)
                return res;
            queue<TreeNode*> q;
            q.push(root);
            q.push(NULL);
            vector<int> level;
            while (!q.empty()) {
                TreeNode *node = q.front();
                q.pop();
                if (node) {
                    level.push_back(node -> val);
                    if (node -> left)
                        q.push(node -> left);
                    if (node -> right)
                        q.push(node -> right);
                } else {
                    res.push_back(level);
                    level.clear();
                    if (!q.empty())
                        q.push(NULL);
                }
            }
            reverse(res.begin(), res.end());
            return res;
        }
    };
    
    

    解题描述

    这道题题意是,对二叉树进行层次遍历,但是要求是自底向上地遍历。上面给出的解法还是跟自顶向下的遍历基本相同,只是在返回结果之前对结果进行一个反转。

  • 相关阅读:
    装饰器和迭代器
    闭包函数
    函数对象
    Python函数
    函数的基本使用
    文件处理
    量化策略
    Android--生命周期
    算法转AI平台工程师记录-0
    python3.6安装
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8385298.html
Copyright © 2020-2023  润新知