Main topic:
Very simple, just need to find the maximum depth of a binary tree, it seems that there is no time and space requirements.
Solution Method:
More simple, only need to follow the width first method to find, here I use a queue to save the node to be expanded, B to save a expanded node, and then use the T intermediate variable to exchange A and B, until a queue is empty, the end.
Note that the boundary condition, when Root=null, should return 0.
#include <iostream>#include <queue>using namespace STD;//definition for a binary tree node.structTreeNode {intVal TreeNode *left; TreeNode *right; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public:intMaxDepth (treenode* root) {intdeep=0; queue<TreeNode*>A queue<TreeNode*>b queue<TreeNode*>Tif(root!=null) deep=deep+1;Else returnDeep A.push (root); while(!a.empty ()) {//When at least one of the two queues is not empty, //List all sub-nodes in a //Put the child node of a in B, //Exchange A and B while(!a.empty ()) {treenode* node=a.front ();if(node->left!=null) B.push (node->left);if(node->right!=null) B.push (node->right); A.pop (); } t=a; A=b; b=t;if(!a.empty ()) deep=deep+1; }returnDeep }};intMain () {cout<<"Just copy the header file and the solution class.!"<< Endl;//test case, compare trouble, do not write, above code remove struct definition can AC return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Practice-Finding the depth of a binary tree-maximu Depth of binary trees