Binary Tree Level Order Traversal II

来源:互联网 发布:java爬虫技术视频教程 编辑:程序博客网 时间:2024/05/29 14:33

c++

/** * 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 == nullptr)            return vector<vector<int>>(0);        vector<vector<int>> res;        getLeaf(root, res, 0);        reverse(res.begin(), res.end());        return res;    }private:    void getLeaf(const TreeNode* root, vector<vector<int>> &res, int depth) {        depth++;        if (res.size() < depth) {            vector<int> tmp(1,root->val);            res.push_back(tmp);        }        else {            res[depth - 1].push_back(root->val);        }        if (root->left == nullptr && root->right == nullptr)            return;        if (root->left != nullptr)            getLeaf(root->left, res, depth);        if (root->right != nullptr)            getLeaf(root->right, res, depth);    }};

python

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def levelOrderBottom(self, root):        """        :type root: TreeNode        :rtype: List[List[int]]        """        if not root:            return []        res = []        self.getLeaf(root, res, 0)        return res[::-1]    def getLeaf(self, root, res, depth):        depth += 1        if len(res) < depth:            tmp = [root.val]            res.append(tmp)        else:            res[depth-1].append(root.val)        if not root.left and not root.right:            return        if root.left:            self.getLeaf(root.left, res, depth)        if root.right:            self.getLeaf(root.right, res, depth)
0 0
原创粉丝点击