Skip to content

107.Binary Tree Level Order Traversal II

难度Easy

刷题内容

原题连接

  • https://leetcode.com/problems/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]
]

˼·1 **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(n)***

����һ�����͵�BFS��Ŀ����һ�ַ������õ��ǵݹ�ķ������Ƚ�����

/**
 * 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> > levelOrderBottom(TreeNode* root) {
        if(!root)
        {
            vector<vector<int> > ret;
            return ret;
        }
        vector<int> v;
        v.push_back(root ->val);
        vector<vector<int> > temp1 = levelOrderBottom(root ->left);
        vector<vector<int> > temp2 = levelOrderBottom(root ->right);
        int pos1 = temp1.size() - 1;
        int pos2 = temp2.size() - 1;
        while(pos1 >= 0  && pos2 >= 0)
        {
            temp1[pos1].insert(temp1[pos1].end(),temp2[pos2].begin(),temp2[pos2].end());
            --pos1;
            --pos2;
        }
        if(pos2 >= 0)
        {
            auto pos = temp2.begin() + pos2 + 1;
            temp1.insert(temp1.begin(),temp2.begin(),pos);
        }
        temp1.push_back(v);
        return temp1;
    }
};

˼·2 **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(n)***

�ڶ��ָĽ��ķ����õ�������ջ�Ĵ��淽ʽ

/**
 * 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>> levelOrderBottom(TreeNode* root) {
        vector<vector<int> > ret;
        if(root != nullptr)
        {
            vector<TreeNode> v;
            v.push_back(*root);
            judge(v,ret);
        }
        return ret;
    }
    void judge(vector<TreeNode>& v,vector<vector<int> >& ret)
    {
        vector<TreeNode> v1;
        vector<int> v2;
        for(int i = 0;i < v.size();i++)
        {
            v2.push_back(v[i].val);
            if(v[i].left != nullptr)
                v1.push_back(*(v[i].left));
            if(v[i].right != nullptr)
                v1.push_back(*(v[i].right));
        }
        if(v1.size())
            judge(v1,ret);
        ret.push_back(v2);
    }
};


回到顶部