Utopi
a

二叉树的最大深度

Essential:Recursive

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree

[3,9,20,null,null,15,7]
,

3 / \ 9 20 / \ 15 7

return its depth = 3.

Mine

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int maxDepth(TreeNode root) { if(root==null){ return 0; } int left=maxDepth(root.left)+1; int right=maxDepth(root.right)+1; return Math.max(left,right); } }

Discussion

第一种方法:BFS广度优先搜索,使用双端队列deque(因为性能比另外两种Queue好得多),在大循环内对二叉树的每个层做一次遍历,

range(len(queue))
使只遍历当前的层,每次大循环
ans
加1。由于每个节点仅访问一次,所以时间复杂度
O(n)

import collections class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 queue = collections.deque() queue.append(root) ans = 0 while queue: ans += 1 for _ in range(len(queue)): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) return ans

第二种方法:DFS深度优先搜索,利用递归的栈,借助

level
标记当前层,由于每个节点仅访问一次,所以时间复杂度
O(n)

class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 self.ans = 0 self._dfs(root, 0) return self.ans def _dfs(self, node, level): if not node: return if self.ans < level + 1: self.ans = level + 1 self._dfs(node.left, level + 1) self._dfs(node.right, level + 1)

第三种方法:DFS+分治,虽然代码简洁但耗时比上面两种方法都久

class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

C语言,经典算法了

/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int maxDepth(struct TreeNode* root){ if(root == NULL) return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); return left>right?left+1:right+1; }