[LeetCode-104] Maximum Depth of Binary Tree(二叉树最大深度)

来源:互联网 发布:cheat engine 6.3 mac 编辑:程序博客网 时间:2024/04/29 22:27

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.

【分析】
本题就是求解二叉树的深度:
递归解法:
(1)如果二叉树为空,二叉树的深度为0
(2)如果二叉树不为空,二叉树的深度 = max(左子树深度, 右子树深度) + 1

/** * 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 depthLeft = maxDepth(root->left);    int depthRight = maxDepth(root->right);    return depthLeft > depthRight ? (depthLeft + 1) : (depthRight + 1); }
1 0
原创粉丝点击