給定一個二叉樹,返回其節點值自底向上的條理遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)

例如:
給定二叉樹 [3,9,20,null,null,15,7],

3
/ \
9  20
/  \
15   7

返回其自底向上的條理遍歷為:

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

解題思緒:首先temp暫且紀錄條理遍歷每一層的結點值,當遍歷到下一層的結點時就將temp紀錄到result中.

代碼實現

Spring注解配置和xml配置優缺點比較


/**
 * 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> > result;   //紀錄每一層的節點值
        if(root == NULL)
        return result;
        queue<pair<TreeNode*,int> > Queue;
        vector<int> temp;   //暫且紀錄每一層的節點值
        Queue.push(make_pair(root,0));
        while(!Queue.empty())
        {
            TreeNode* node = Queue.front().first;
            int step = Queue.front().second;
            Queue.pop();
            if(result.size() == step - 1)
            {
                result.push_back(temp);
                temp.clear();
                temp.push_back(node->val);
            }
            else
            {
                temp.push_back(node->val);
            }
            if(node->left)
            Queue.push(make_pair(node->left, step + 1));
            if(node->right)
            Queue.push(make_pair(node->right, step + 1));
        }
        result.push_back(temp);
        reverse(result.begin(),result.end());
        return result;
    }
};