求给定二叉树的最大深度,
深度是指树的根节点到任一叶子节点路径上节点的数量。
最大深度是所有叶子节点的深度的最大值。
(注:叶子节点是指没有子节点的节点。)
数据范围:
,树上每个节点的val满足 
要求: 空间复杂度
,时间复杂度 )
要求: 空间复杂度
int maxDepth(struct TreeNode* root ) { if (root == NULL) return 0; int a = maxDepth(root->left) + 1; int b = maxDepth(root->right) + 1; return a > b? a:b; }
int maxDepth(struct TreeNode* root ) { // write code here //无左右结点及无深度,返回0 if(root==NULL) { return 0; } else { //递归遍历左右节点的深度 int leftDepth=maxDepth(root->left); int rightDepth=maxDepth(root->right); //左右深度比较,返回较大的深度,+1(算上跟结点) return leftDepth>rightDepth?leftDepth+1:rightDepth+1; } }
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ //递归算法 int maxDepth(struct TreeNode* root ) { // write code here if(root==NULL) return 0;//递归到空时,返回0 int m=maxDepth(root->left);//递归左子树,m++ int n=maxDepth(root->right);//递归右子树,n++ if(m>n) return m+1; else return n+1; }
//递归遍历一层一层往下走,并且每进入下一层进行一次深度的比较, //最后看记录的最深度就知道二叉树的最深度 int maxdeep=0;//记录当前最深度 int max(int a,int b) { return a>b?a:b; } void Tree(struct TreeNode* root,int deep) { if(root==NULL) { return; } maxdeep=max(maxdeep,deep);//比较深度 Tree(root->left,deep+1);//进入下一层左子树,层数加一 Tree(root->right,deep+1);//进入下一层右子树,层数加一 } int maxDepth(struct TreeNode* root) { Tree(root,1); return maxdeep; }
设置2个变量来保存最大深度和当前深度,遇到叶子节点则后退
static int total=0; static int now = 0; int maxDepth(struct TreeNode* root ) { // write code here if(root == NULL) { return 0; } else { now++; if(now > total) { total=now; } if(root->left != NULL) { maxDepth(root->left); } if(root->right != NULL) { maxDepth(root->right); } now--; } return total; }
static int g_dp; static void dfs_dp(struct TreeNode *root, int deep) { if (root == NULL) { if (g_dp < deep) g_dp = deep; return; } dfs_dp(root->left, deep + 1); dfs_dp(root->right, deep + 1); } int maxDepth(struct TreeNode* root ) { g_dp = 0; dfs_dp(root, 0); return g_dp; }
int maxDepth(struct TreeNode* root ) { int rdp, ldp; if (root == NULL) return 0; rdp = maxDepth(root->right); ldp = maxDepth(root->left); return rdp > ldp ? rdp + 1 : ldp + 1; }