leetcode刷题。总结,记录,备忘 104
2015-05-23 21:45
176 查看
leetcode104题,计算二叉树的深度。
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返回给上一层。
第二种方法使用c++中的队列容器,使用一个int型变量来记录当前层是否遍历完,如果遍历完,深度+1,否则继续遍历当前层。
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返回给上一层。
int maxDepth(strut TreeNode * root) { if (root == NULL) { return 0; } int left = maxDepth(root->left); int right = maxDepth(root->right); return left > right ? left + 1 : right + 1; }
第二种方法使用c++中的队列容器,使用一个int型变量来记录当前层是否遍历完,如果遍历完,深度+1,否则继续遍历当前层。
int maxDepth1(struct TreeNode * root) { if (NULL == root) { return 0; } queue<TreeNode*> que; int count = 1; int treedepth = 0; que.push(root); while (!que.empty()) { TreeNode * temp = que.front(); que.pop(); if (temp->left) que.push(temp->left); if (temp->right) que.push(temp->right); count--; if (count == 0) { treedepth++; count = que.size(); } } return treedepth; }
相关文章推荐
- leetcode刷题,总结,记录,备忘 90
- leetcode刷题,总结,记录,备忘, 279
- leetcode刷题,总结,记录,备忘 80
- leetcode刷题,总结,记录,备忘 328
- leetcode刷题,总结,记录,备忘 39
- leetcode刷题,总结,记录,备忘 350
- leetcode刷题,总结,记录,备忘238
- leetcode刷题, 总结,记录,备忘 171
- leetcode刷题,总结,记录 ,备忘48
- leetcode刷题, 总结,记录, 备忘 230
- leetcode刷题,总结,记录,备忘 329
- leetcode刷题,总结,记录,备忘 383
- leetcode刷题,总结,记录 ,备忘 172
- leetcode刷题,总结,记录,备忘202
- leetcode刷题,总结,记录,备忘235
- leetcode刷题, 总结,记录, 备忘142
- leetcode刷题,总结,记录,备忘111
- leetcode刷题。记录,总结,备忘。217
- leetcode刷题,总结,记录,备忘109
- leetcode刷题,总结,记录,备忘89