public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
DFS(深度优先搜索)策略的示例
时间复杂度:我们每个结点只访问一次,因此时间复杂度为 O(N)O(N),
其中 NN 是结点的数量。
空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用 NN 次(树的高度),因此保持调用栈的存储将是 O(N)O(N)。但在最好的情况下(树是完全平衡的),树的高度将是 \log(N)log(N)。因此,在这种情况下的空间复杂度将是 O(\log(N))O(log(N))。
public class BinaryTreeDepth {
//树的最大深度等于当前节点深度 1 加左右子树最大深度:1+max(left_height,right_height)
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int left_height = maxDepth(root.left);
int right_height = maxDepth(root.right);
return Math.max(left_height, right_height) + 1;
}
}
}