0. 题目
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.
1. c++版本
方法1递归方式,其实左子树或者右子树的最大深度+当前root
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root)
return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
版本2,利用层序遍历, 求二叉树的深度!
int maxDepth(TreeNode* root) {
queue<TreeNode *> fatherQueue, childQueue;
int depth=0;
if (root) {
fatherQueue.push(root);
depth++;
}
while (!fatherQueue.empty()) {
root = fatherQueue.front();
fatherQueue.pop();
if (root->left)
childQueue.push(root->left);
if (root->right)
childQueue.push(root->right);
if (fatherQueue.empty() && !childQueue.empty()) {
swap(fatherQueue, childQueue);
depth++;
}
}
return depth;
}
2. python版本
如何c++版本,采用递归方式
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
网友评论