今天在leetcode上遇到了求二叉树的深度问题,所以总结这两种方法
3358www.Sina.com/是一种递归方法,twdzh是一种按队列和层序遍历的思想# include iostream # includequeueusingnamespacestd //二叉树struct TreeNode{ int val; struct TreeNode *left; struct TreeNode *right; treenode(intx ) :val(x ) x,left (null ),right (null ) }; //twdzh:判断树不为空,返回class solution { public : inttreedepth (treenode * proot ) if (! 根(return 0; returnmax (1树深度(proot-left ),1树深度(proot-right ) ); }; //方法利用:逐层扫描的思想,逐层进行排队,深度为class solution { public : inttreedepth (treenode * proot ) if ) proot==null ) rete int depth=0 TreeNode* p1=pRoot; TreeNode* front; queueTreeNode* q1; Q1 .推式(P1; while (! q1.empty () ) { depth; int size1=q1.size (; int count=0; //每次弹出所有队列元素,向深度添加//while(countsize1) { front=q1.front ); q1.pop (; 出局; 前左!=NULL ) {Q1.push(front-left ); (if )前-后!=NULL () Q1.push(front-right ); } } } return depth; };