1. 程式人生 > >leetcode 107 Binary Tree Level Order Traversal II

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

和第102題類似,給定一個二叉樹,返回其層次遍歷的結果,每層單獨放到一起。不過本題返回的結果是最底層的子節點到最上面的根節點的結果,可以直接拿102題的結果,然後直接reverse就好。如果這樣的話,那就太沒意思了!對程式碼稍作改動,在開始時直接開闢好深度大小的vector,然後dfs每層遍歷時,在結果中反向進行插入值就好,這樣執行效率就提高了很多,程式碼記錄如下:

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        int depth = dfsDepth(root);
        vector<vector<int>> ret(depth, vector<int>());
        bfsLevelOrder(ret, depth - 1, root);
        return ret;
    }
    
    void bfsLevelOrder(vector<vector<int>> &ret, int level, TreeNode *root)
    {
        if(!root)
            return;
        if(ret.size() <= level)
        {
            ret.insert(ret.begin(), {});
        }
        ret[level].push_back(root->val);
        if(root->left)
            bfsLevelOrder(ret, level - 1, root->left);
        if(root->right)
            bfsLevelOrder(ret, level - 1, root->right);
    }
    
    int dfsDepth(TreeNode* root)
    {
        if(!root)
            return 0;
        return max(dfsDepth(root->left), dfsDepth(root->right)) + 1;
    }
};