首页 > 编程知识 正文

二叉树的题目,二叉树 面试题

时间:2023-05-03 13:00:45 阅读:160282 作者:2891

主题说明在线提交至:点击跳转

方法一(递归intmaxdepth(treenode*root ) if ) root==null ) return 0; intleftdepth=最大深度(根深度) 1; intrightdepth=最大深度(root-right ) 1; return leftDepth rightDepth? leftDepth : rightDepth; }单行版本:

intmaxdepth(treenode*root ) { return root==NULL? 0:最大深度(root-left ) 1,最大深度root-right; }提交结果

方法2 )深度优先(栈)栈实现深度优先遍历,将二叉树的上层节点推入栈底后操作栈顶的下层节点,最后操作栈底的上层节点,可以利用栈的特性实现深度优先遍历

将根节点进行堆栈,将当前节点深度1堆栈从堆栈的起始节点取出的同时获取堆栈节点的深度,基于该节点将与子节点对应的深度进行堆栈。 如果此时取出的节点的深度大于res_depth,则更新res_depth。 否则,堆栈空intmaxdepth(treenode*root ) stacktreenode ); 堆栈深度; int res_depth=0; if (根!=null(s.push ) root; Depth.push(1; } while (! s.empty () { TreeNode* node=s.top; s.pop (; int temp_depth=depth.top (; depth.pop (; res_depth=temp_depth res_depth? temp_depth : res_depth; if (节点左!=null(s.push(node-left ); EPTH.push(temp_depth1); 因为temp_depth获得了上一层的深度,所以在堆栈子节点后,再堆栈temp_depth 1) }if(node-right!=null(s.push(node-right ); EPTH.push(temp_depth1); //此时堆栈的是当前堆栈节点的深度} } return res_depth; 提交结果:

方法3 )利用广度优先(队列)分层扫描原理求解深度

根节点的先进先出队列将队列中节点的子节点进行排队,深度为1。 在遍历队列的同时,遍历的节点将具有队列intmaxdepth(treenode*root ) { queueTreeNode* q; int depth=0 if (根!=NULL () q.push )根; } while (! q.empty () { TreeNode* node=q.front; int len=q.size (; //得到的是该层的节点个数depth; //一次for循环的结束意味着所有的下级节点都可以通过遍历队列得到的上级节点来实现队列for(intI=0; ilen; I({treenode*temp=q.front ); q.pop (; 临时左!=null}{q.push(temp-left ); (if ) temp-right!=null}{q.push(temp-right ); } } } return depth; 提交结果:

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