地址:http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
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.
思路:dfs遍历,记录当前节点的深度并与max_depth比较。手写WA了几次,第一次没有考虑root为NULL的情况,第二次没有考虑root的左右孩子都是NULL的情况,
第三次因为不清楚Leetcode是一个程序中多次调类方法来测试数据(如果是pat就不用了),所以全局变量没有重置,即maxDepth中max_depth = 0 没写。
此题应该是常考题型。
参考代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int max_depth = 0;
void dfs(TreeNode* node, int depth)
{
if(node)
{
++depth;
if(node->left)
{
dfs(node->left, depth);
}
if(node->right)
{
dfs(node->right, depth);
}
}
max_depth = max_depth > depth ? max_depth : depth;
}
class Solution {
public:
int maxDepth(TreeNode *root) {
max_depth = 0;
dfs(root, 0);
return max_depth;
}
};
//SECOND TRIAL, bfsclass Solution {public :int maxDepth ( TreeNode * root ) {if ( ! root )return 0 ;queue < TreeNode *> treeq ;treeq . push ( root );TreeNode * cur = NULL ;int ans = 0 ;while ( ! treeq . empty ()){int sz = treeq . size ();++ ans ;while ( sz -- ){cur = treeq . front ();treeq . pop ();if ( cur -> left )treeq . push ( cur -> left );if ( cur -> right )treeq . push ( cur -> right );}}return ans ;}};
python:
# Definition for a binary tree node# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = None
class Solution :# @param root, a tree node# @return an integerdef maxDepth ( self , root ):if not root :return 0q = [ root ]ans = 0while q :sz = len ( q )ans += 1while sz :sz -= 1cur = q . pop ()if cur . left :q . insert ( 0 , cur . left )if cur . right :q . insert ( 0 , cur . right )return ans