【树】二叉树的深度

您所在的位置:网站首页 层序遍历二叉树算法 【树】二叉树的深度

【树】二叉树的深度

2024-07-16 07:24| 来源: 网络整理| 查看: 265

给定二叉树的深度

题目描述:

minimum-depth-of-binary-tree

求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node

算法思想:通过层序遍历的算法思想,借助队列实现二叉树层序遍历。

                  每次遍历当前一层中所有结点,存在三种情况:

                  (1) 存在左子树

                  (2) 存在右子树

                  (3) 左右子树都不存在,返回当前二叉树最小深度值

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int run(TreeNode *root) { if(root==NULL) return 0; int depth=0; queuemyqueue; //初始化队列 myqueue.push(root); //入队 TreeNode *node; while(!myqueue.empty()){ //队列不为空 int size=myqueue.size(); //当前队列中存在结点的个数 depth++; //层数+1 for(int i=0;ileft==NULL&&node->right==NULL) return depth; //左右子树都为空,即为最小深度 if(node->left!=NULL) //存在左子树 myqueue.push(node->left); if(node->right!=NULL) //存在右子树 myqueue.push(node->right); } } } };

题目描述:

maximum-depth-of-binary-tree

求给定二叉树的最大深度,

最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

算法思想:通过层序遍历的算法思想,借助队列实现二叉树层序遍历。

                  每次遍历当前一层中所有结点,存在三种情况:

                  (1) 存在左子树

                  (2) 存在右子树

                  (3) 左右子树都不存在,更新二叉树最大深度值

                  最后,返回二叉树最大深度值

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { int maxdepth=0; //记录二叉树最终最大深度值 return dfs(root,maxdepth); } int dfs(TreeNode *root,int maxdepth) { if(root==NULL) return 0; int depth=0; //记录当前二叉树最大深度值 queuemyqueue; myqueue.push(root); TreeNode *node; while(!myqueue.empty()){ int size=myqueue.size(); depth++; for(int i=0;ileft==NULL&&node->right==NULL) maxdepth=max(depth,maxdepth); //取较大值 if(node->left!=NULL) myqueue.push(node->left); if(node->right!=NULL) myqueue.push(node->right); } //for } //while return maxdepth; //返回二叉树最大深度值 } };

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3