LintCode 第97题 二叉树的最大深度 【分治算法】
2017-12-06 14:35
357 查看
题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例
给出一棵如下的二叉树:
这个二叉树的最大深度为
解题思路:
使用递归的思想,递归函数返回当前节点左右子节点的深度大的那一个。
实现代码:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例
给出一棵如下的二叉树:
1 / \ 2 3 / \ 4 5
这个二叉树的最大深度为
3.
解题思路:
使用递归的思想,递归函数返回当前节点左右子节点的深度大的那一个。
实现代码:
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; typedef char ElemType; typedef struct BinaryTreeNode{ char value; struct BinaryTreeNode *lchild,*rchild; }BinaryTreeNode,*BinaryTree; BinaryTreeNode * CreatBiTree() { BinaryTreeNode * node; char data; cin>>data; if (data == '#') { node = NULL; } else { node = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));//new BinaryTreeNode; node->value = data; node->lchild = CreatBiTree(); node->rchild = CreatBiTree(); } return node; } int returnMaxDepth(BinaryTreeNode *node){ if (node == NULL) { return 0; } int leftDepth = returnMaxDepth(node->lchild); int rightDepth = returnMaxDepth(node->rchild); return leftDepth > rightDepth?leftDepth+1:rightDepth+1; } int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; BinaryTreeNode * rootNode = CreatBiTree(); int maxDepth = returnMaxDepth(rootNode); return 0; }
相关文章推荐
- 二叉树的最大深度(LintCode)
- [lintcode]二叉树最大深度和最小深度
- LintCode [递归]97.二叉树的最大深度
- LintCode-97.二叉树的最大深度
- [LintCode]97.二叉树的最大深度
- 二叉树的最大深度-LintCode
- python_lintcode_97二叉树的最大深度 _155二叉树的最小深度
- [LintCode] Maximum Depth of Binary Tree 二叉树的最大深度
- [lintcode]二叉树的最大深度
- [Lintcode] #97 二叉树的最大深度
- LintCode_097_二叉树的最大深度
- 二叉树的最大深度-LintCode
- LintCode_097_二叉树的最大深度
- Lintcode 97.二叉树的最大深度
- LintCode 二叉树的最大深度
- LintCode-剑指Offer-(97)二叉树的最大深度
- 【LintCode 简单】97. 二叉树的最大深度
- Lintcode——97. 二叉树的最大深度
- lintcode,二叉树的最大深度
- LintCode【简单】97. 二叉树的最大深度 。代码及思路