二叉树的最大(小)深度
来源:互联网 发布:java架构师工作内容 编辑:程序博客网 时间:2024/06/06 16:56
描述:给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例
给出一棵如下的二叉树:
思路:想到要采用递归调用的方法,但是不知道从何下手。后面参考网上,对左右子树都进行Max函数的调用,然后进行比较,较大者即为深度减1的量。
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root: The root of binary tree. * @return: An integer */ int maxDepth(TreeNode *root) { // write your code here if(root == NULL) return 0; int left=maxDepth(root->left); int right=maxDepth(root->right); return max(left,right)+1; }};
拓展:有最大深度,自然而然有最小深度。
思路:同样采用递归调用。只是有一点不同:因为深度是必须到叶子节点的距离,因此使用深度遍历时,不能单纯的比较左右子树的递归结果返回较小值,因为对于有单个孩子为空的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。因此,当发现当前处理的节点有单个孩子是空时,返回一个极大值INT_MAX,防止其干扰结果。
class Solution {public: int minDepth(TreeNode *root) { if(!root) return 0; if(!root -> left && !root -> right) return 1; //Leaf means should return depth. int leftDepth = minDepth(root -> left); leftDepth = (leftDepth == 1 ? INT_MAX : leftDepth); int rightDepth = minDepth(root -> right); rightDepth = (rightDepth == 1 ? INT_MAX : rightDepth); //If only one child returns 1, means this is not leaf, it does not return depth. return min(leftDepth, rightDepth)+1; }};
阅读全文
0 0
- 二叉树的最大(小)深度
- 非递归求取二叉树的最大/小深度
- 二叉树的最大深度(LintCode)
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 在http服务器里使用协程
- Epson机械手简单实例编程
- ajax请求
- spring 事务(1事务的基本理解和实现声明式事务管理)
- GIT
- 二叉树的最大(小)深度
- pc端前端页面适应不同分辨率的问题
- 最短路 HDU-2544【斩获最短路溢出的问题】
- snapdragon camera 缩略图各个场景显示介绍
- 也来谈谈币圈众筹
- PyQt5笔记
- HDU 6073 Matching In Multiplication
- 2017.8.1拼多多内推内推笔试题(1)—最大乘积的求取(分治求K大(小))
- response.encodeURL的用法 把 Session ID 添加到 URL 信息中