LeetCode算法题104:二叉树的最大深度解析

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

这个题的解析我讲不过官方解答,它有图—>[link]https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/
至少递归法是没什么说得了,迭代法的话上网搜了一下,二叉树的遍历可以用栈来进行,和递归一个思路,所以还是那句话,全部遍历一般是用栈的,如果判断条件,从根到叶中间可以直接出去,用队列应该效率更高一些。层次遍历一般用栈遍历的方法。也有DFS算法的思想,毕竟是最大深度。(我猜如果是最小深度应该可以用BFS的思想,后面有题可以验证一下)。
DFS思想就是朝着一条路走到黑,走不通就返回去朝另一条路走到黑,这里的代码是从右边先一条路走到底,然后往左移。
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 == NULL)
            return 0;
        int leftDepth = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
        return (leftDepth>rightDepth?leftDepth:rightDepth) + 1;
    }
};

python3源代码:(迭代法)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        stack = []
        if root!=None:
            stack.append((1, root))
        depth = 0 
        while stack!=[]:
            currDepth, root = stack.pop()
            if root!=None:
                depth = max(currDepth, depth)
                stack.append((currDepth+1, root.left))
                stack.append((currDepth+1, root.right))
        return depth

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/83650453