美文网首页
107. Binary Tree Level Order Tra

107. Binary Tree Level Order Tra

作者: YellowLayne | 来源:发表于2017-06-19 14:35 被阅读0次

1.描述

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

2.方法一

2.1 分析

从上到下依次遍历

2.2 代码

/**
 * 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>> tree;
        if (NULL == root) return tree;
        
        vector<struct TreeNode*> cur_level, next_level;
        cur_level.push_back(root);
        
        vector<int> tmp;
        tmp.push_back(root->val);
        tree.push_back(tmp);
        
        int level = 0;
        while (level < tree.size()) {
            next_level.clear();
            vector<int> vct_level;
            
            for (int i = 0; i < cur_level.size(); ++i) {
                if (NULL != cur_level[i]->left) {
                    next_level.push_back(cur_level[i]->left);
                    vct_level.push_back(cur_level[i]->left->val);
                }
                if (NULL != cur_level[i]->right) {
                    next_level.push_back(cur_level[i]->right);
                    vct_level.push_back(cur_level[i]->right->val);
                }
            }
            cur_level.swap(next_level);
            if (!vct_level.empty()) {
                tree.push_back(vct_level);
            }
            ++level;
        }
        reverse(tree.begin(), tree.end());
        return tree;
    }
};

3.方法二

3.1 分析

先获取树的高度,然后深度优先遍历

3.2 代码

/**
 * 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:
    int getDepth(TreeNode* root) {
        if (NULL == root) return 0;
        int left = getDepth(root->left);
        int right = getDepth(root->right);
        return left > right ? left + 1 : right+1;
    }

    void DFS(vector<vector<int>> &vct, int level, TreeNode* root) {
        if (NULL == root) return ;
        vct[level].push_back(root->val);
        DFS(vct, level - 1, root->left);
        DFS(vct, level - 1, root->right);
    }

    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        int depth = getDepth(root);
        vector<vector<int>> vct(depth);
        if (0 == depth) return vct;
        DFS(vct, depth - 1, root);
        return vct;
    }
};

相关文章

网友评论

      本文标题:107. Binary Tree Level Order Tra

      本文链接:https://www.haomeiwen.com/subject/sdigqxtx.html