首页 > 编程知识 正文

二叉树前序中序求后序,二叉树节点深度

时间:2023-05-05 14:21:13 阅读:166776 作者:3142

主题说明:给出二叉树,找出叶节点深度的中间值。

叶节点的深度是从根节点到叶节点的路径上的节点数。

最小深度是从根节点到最近的叶节点的路径上的节点数。

最大深度是从根节点到最远的叶节点的路径上的节点数。

中间值是叶子节点的最小深度和最大深度的平均值。

说明:叶节点是指没有子节点的节点。

样品:

给定二叉树[ 3,9,20,null,null,15,7 ],

3

//

9 20

//

15 7

的最小深度为2,最大深度为3时,中间值为(2)3)/2=2.5

算法思路:此题的实现思路可以结合力扣上两道简单的树的题目。分别为:

二叉树的最小深度二叉树的最大深度二叉树的最大深度:算法思路:

特殊情况下的处理:如果root为空,则返回0;

求二叉树的最大深度:以深度优先搜索树的左边的子树和右边的子树,取两者的最大值,再加1。 添加1的理由是需要添加现在的节点,理解为是为了添加需要递归的节点。

代码实现:递归图解:

intmaxdepth(treenode*root ) if ) root==nullptr ) return 0; returnmax (最大深度(root-left ),最大深度root-right ) 1; }

不熟悉树的实际情况是完整的代码如下。

class solution { public : intgetdepth (treenode * node ) if ) node==null } return 0; intleft depth=get depth (node-left ); //左intrightdepth=get depth (node-right ); //右intdepth=1max(leftdepth,rightDepth ); //中返回深度; }intmaxdepth(treenode*root ) returngetdepth ) root; }; 二叉树的最小深度:看完最大深度后,看最小深度,第一次写很容易

intmaxdepth(treenode*root ) if ) root==nullptr ) return 0; returnmax (最大深度(root-left ),最大深度root-right ) 1; 但是这是错误的。 查看主题,主题的最小深度被定义为最小深度从根节点到最近叶子节点的路径上的节点数。

的写法是,如果一棵树的左子为空,只有右子为空,则此时的最小深度不是1,而是右子树的最小深度。

class solution { public : int mindepth (treenode * root ) if ) root==null } return 0; root-left==空root-right!=null((/如果左边的子树为空,右边的子树不为空,则返回1 mindepth (root-right ); //返回的是右边子树的最小深度(if(root-left!=nullroot-right==null((/左边的子树不是空的,右边的子树是空的return1mindepth(root-left ); //返回的是左部分树的最小深度(return1min(mindepth(root-left ),mindepth ) root-right ) ); //左右子树没有空闲时,返回左右子树中的最小值。 }; 最终代码:代码实现: # include iostream # include vector # include algorithm # include unordered _ map # include queue # includeset # inclue TreeNode *left; TreeNode *right; treenode(:val )0)、left (null )、right (treenode ) intx ) :val ) x )、left (null )、right ) nu null class ssoss returnmax (最大深度(root-left ),最大深度root-right ) 1; }intmindepth(treenode*root ) if ) root==null ) return 0; root-left==空root-right!=null((/如果左边的子树为空,右边的子树不为空,则返回1 mindepth (root-right ); //返回的是右边子树的最小深度(if(root-left!=nullroot-right==null((/左边的子树不是空的,右边的子树是空的return1mindepth(root-left ); //返回的是左部分树的最小深度(return1min(mindepth(root-left ),mindepth ) root-right ) ); //左右子树没有空闲时,返回左右子树中的最小值。 }doubleavedepth(treenode*root ) {double res; res=(maxdepth(root ) mindepth (root ) )/2; 返回结果; }; TreeNode* inputTree () {int n,count=0; char item[100]; cin n; if(n==0)返回空值; cin item; treenode*root=newtreenode(atoi ) item ); 出局; queueTreeNode* nodeQueue; nodequeue.push(root; while(countn ) { treenode * node=node queue.front }; nodeQueue.pop (; cin item; 出局; if (strcmp (项目,' null '!=0) intleftnumber=atoi(item ); node-left=new treenode (left number ); nodequeue.push(node-left; }if(count==n ) break; cin item; 出局; if (strcmp (项目,' null '!=0) intrightnumber=atoi(item ); node-right=new treenode (right number; nodequeue.push(node-right; } }返回根; }int main () {TreeNode* root; root=输入树(; double res=Solution ().avedepth ) root; cout res; getchar (; getchar (; }

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