您的位置:首页 > 其它

Leetcode Maximum Depth of Binary Tree

2014-06-22 23:21 274 查看
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.

递归求解

int maxDepth(TreeNode *root){
return root? 1+max(maxDepth(root->left), maxDepth(root->right)) : 0;
}


非递归求解

struct Node{
TreeNode *node;
int depth;
Node(TreeNode *a = NULL , int d = 0):node(a), depth(d);
};

int maxDepth1(TreeNode *root){
if(root == NULL) return 0;
queue<Node> que;
Node  rootNode(root,1);
que.push(rootNode);
int res = 0;
while(!que.empty()){
Node p = que.front();que.pop();
res = p.depth;
if(p.node->left)    que.push(Node(p.node->left,p.depth+1));
if(p.node->right )  que.push(Node(p.node->right,p.depth+1));
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: