二叉树的最大深度-二叉树104-C++&python

  • Post author:
  • Post category:python




算法思想:



DFS

请深度理解递归思想,不懂就画出递归过程图辅助理解。


C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == nullptr) return 0;
        int l = maxDepth(root->left);
        int r = maxDepth(root->right);
        int res = l > r ? l : r;
        return res + 1;
    }
};



BFS


python

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

#
# 
# @param root TreeNode类 
# @return int整型
#
class Solution:
    def maxDepth(self , root ):
        # write code here
        res = 0
        if root == None:
            return res
        queue = [root]
        
        while queue:
            res += 1
            for i in range(len(queue)):
                tmp = queue.pop(0)
                if tmp.left:
                    queue.append(tmp.left)
                if tmp.right:
                    queue.append(tmp.right)
        
        return res



版权声明:本文为VaccyZhu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。