zoukankan      html  css  js  c++  java
  • [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;
        }
    };
    
    

    解题描述

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

  • 相关阅读:
    如何搭建SVN的客户端和使用
    SVN服务器的本地搭建和使用
    grep命令
    cat命令
    cut命令
    yum 命令
    XPath、XQuery 以及 XSLT 函数
    XPath 实例
    XPath 运算符
    XPath Axes(轴)
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8385298.html
Copyright © 2011-2022 走看看