Maximum Depth of Binary Tree

来源:互联网 发布:湖人12年纳什数据 编辑:程序博客网 时间:2024/06/06 05:15

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:    int maxDepth(TreeNode* root) {        if (root == nullptr)            return 0;        getLeaf(root, 0);        return max_depth;    }private:    int max_depth = -1;    void getLeaf(const TreeNode* root, int depth) {        depth++;        if (root->left == nullptr && root->right == nullptr) {            if (max_depth < depth)                max_depth = depth;            return;        }        if (root->left)            getLeaf(root->left, depth);        if (root->right)            getLeaf(root->right, 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 __init__(self):        self.max_depth = -1    def maxDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        if not root:            return 0        self.getLeaf(root, 0)        return self.max_depth    def getLeaf(self, root, depth):        depth += 1        if not root.left and not root.right:            if self.max_depth < depth:                self.max_depth = depth            return        if root.left:            self.getLeaf(root.left, depth)        if root.right:            self.getLeaf(root.right, depth)
0 0
原创粉丝点击