溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

leetCode 107. Binary Tree Level Order Traversal II 二叉樹(shù)層次遍歷反轉(zhuǎn)

發(fā)布時(shí)間:2020-07-02 03:24:57 來(lái)源:網(wǎng)絡(luò) 閱讀:517 作者:313119992 欄目:編程語(yǔ)言

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


解題思路:

此題與Binary Tree Level Order Traversal相似,只是最后的結(jié)果有一個(gè)反轉(zhuǎn)。

參考 http://qiaopeng688.blog.51cto.com/3572484/1834819

代碼如下:

/**
 * 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;
        queue<TreeNode *> current,next;
        vector<int> level;
        if(NULL == root)
            return result;
        current.push(root);
        
        while(current.size())
        {
            while(current.size())
            {
                TreeNode *p;
                p = current.front();
                current.pop();
                level.push_back(p->val);
                if(p->left)
                    next.push(p->left);
                if(p->right)
                    next.push(p->right);
            }
            result.push_back(level);
            level.clear();
            swap(current,next);
        }
        reverse(result.begin(),result.end());
        //相對(duì)與Binary Tree Level Order Traversal只加了這一句。reverse(),反轉(zhuǎn)
        return result;
    }
};


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI