Requirements: Find the depth of the binary tree (the depth of the binary tree is the distance from the farthest leaf node to the root node, i.e. the distance from the root node to the farthest leaf node)
is from the root node down to the farthest leaf node.
There are two ways to solve the idea, a use of DFS, a concept using BFS, as shown in the following code:
1 structTreeNode {2 intVal;3treenode*Left ;4treenode*Right ;5TreeNode (intx): Val (x), left (null), right (null) {}6 };7 8 //the idea of using DFS9 intMaxDepth (TreeNode *root)Ten { One if(NULL = =root) A return 0; - intL = maxDepth (root->Left ); - intR = maxDepth (root->Right ); the - returnL > R? L +1: r+1; - //There's a simpler way to do both of these. - //return 1 + max (maxDepth (Root->left), maxDepth (Root->right)); + } - + //using the BFs method, the queue is introduced A intMaxDepth (TreeNode *root) at { - if(NULL = =root) - return 0; -Queue <treenode *>que; - intNcount =1; - intNdepth =0;//record elements on each layer in the queue in - Que.push (root); to while(!Que.empty ()) { +TreeNode *ptemp =Que.front (); - Que.pop (); theNcount--; * $ if(ptemp->Left )Panax NotoginsengQue.push (ptemp->Left ); - if(ptemp->Right ) theQue.push (ptemp->Right ); + A if(Ncount = =0) { theNdepth + +; +Ncount =que.size (); - } $ } $ returnndepth; -}
Leetcode:maximum Depth of Binary Tree