方法一:递归法求解二叉树深度,递归公式为h(root) = max(h(root->left), h(root->righr)) + 1,递归终止条件为树为空数即root = nullptr。
时间复杂度:二叉树中每个节点都要对其求二叉树最大深度,所以求二叉树最大深度函数执行次数为n,故时间复杂度为O(n)。
空间复杂度:在同一时刻只有一个函数在运行,函数执行过程中只需要几个临时变量,所以空间复杂度为O(1)。
1 int maxDepth(TreeNode* root) { 2 if (root == nullptr) return 0; //递归终止条件,树为空树 3 4 int leftChildTreeHeight = maxDepth(root->left); //左子树高度 5 int rightChildTreeHeight = maxDepth(root->right); //右子树高度 6 int height = ((leftChildTreeHeight > rightChildTreeHeight) ? leftChildTreeHeight : rightChildTreeHeight) + 1; //树的高度等于左右子树高度较大值加1 7 8 return height; 9 }
原文:https://www.cnblogs.com/zpchya/p/10845826.html