首页 > 编程知识 正文

求二叉树最小深度,设计算法求二叉树深度

时间:2023-05-06 15:11:11 阅读:160290 作者:1976

今天在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; };

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。