标签:
Given a binary tree, findits maximum depth.
The maximum depth is thenumber of nodes along the longest path from the root node down to the farthestleaf node.
可用递归,效率低。
这里用类似层次遍历的算法。设置一个队列和两个int变量thiscount和nextcount。
初始thiscount=1nextcount=0分别表示当前层待遍历的节点数和下一层待遍历的节点数。
遍历时根据有几个孩子递增nextcount而递减thiscount,将孩子push入队列。当thiscount==0时,一层遍历完毕,thiscount=nextcount,nextcount=0,同时depth+1.继续下一层的遍历,队列为空时退出。
注意当root节点为空时要返回0.
#pragma once #include<queue> #include<iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; int maxDepth(TreeNode *root) { queue<TreeNode*> q; TreeNode* temp; q.push(root); int thiscount = 1;//q中当前这一层待遍历节点的数量 int nextcount = 0;//q中下一层待遍历的节点的数量 int depth = 0; while (!q.empty()) { if (!root) return 0;//空树,返回0 temp = q.front(); q.pop(); thiscount--; if (temp->left) { q.push(temp->left); nextcount++; } if (temp->right) { q.push(temp->right); nextcount++; } if (thiscount == 0)//该层遍历完毕 { thiscount = nextcount; nextcount = 0; depth++; } } return depth; } void main() { TreeNode *t1 = new TreeNode(1); TreeNode *t2 = new TreeNode(2); TreeNode *t3 = new TreeNode(3); TreeNode *t4 = new TreeNode(4); TreeNode *t5 = new TreeNode(5); TreeNode *t6 = new TreeNode(6); TreeNode *t7 = new TreeNode(7); TreeNode *t8 = new TreeNode(8); TreeNode *t9 = NULL; t1->left = t2; t1->right= t3; t3->left = t4; t4->left = t5; t4->right = t6; t6->left = t7; t7->left = t8; cout << maxDepth(t1) << endl; system("pause"); }
104.Maximum Depth of Binary Tree
标签:
原文地址:http://blog.csdn.net/hgqqtql/article/details/43278699