二叉树的深度
- 参与人数:3367时间限制:1秒空间限制:32768K
- 算法知识视频讲解
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
递归的代码量小,我在本地把程序运行起来打断点跑了跑。
测试用的二叉树形状如下:
// 33.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
if (pRoot == NULL) return 0;
return getDepth(pRoot);
}
int getDepth(TreeNode* pNode) {
if (pNode == NULL) return 0;
int depthLeft = getDepth(pNode->left);
int depthRight = getDepth(pNode->right);
return depthLeft > depthRight ? depthLeft + 1 : depthRight + 1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode root(1);
TreeNode rootLeft(2);
TreeNode rootRight(3);
TreeNode rootLeftLeft(4);
TreeNode rootLeftRight(5);
TreeNode rootLeftRightLeft(7);
TreeNode rootRightRight(6);
root.left = &rootLeft;
root.right = &rootRight;
rootLeft.left = &rootLeftLeft;
rootLeft.right = &rootLeftRight;
rootLeftRight.left = &rootLeftRightLeft;
rootRight.right = &rootRightRight;
Solution s;
int result = s.getDepth(&root);
return 0;
}
第二次做:
做这种题思路一定要灵活~
// 二叉树的深度.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
if (pRoot == NULL) return 0;
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
return left > right ? left + 1 : right + 1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode root(1);
TreeNode rootLeft(2);
TreeNode rootRight(3);
TreeNode rootLeftLeft(4);
TreeNode rootLeftRight(5);
TreeNode rootLeftRightLeft(7);
TreeNode rootRightRight(6);
root.left = &rootLeft;
root.right = &rootRight;
rootLeft.left = &rootLeftLeft;
rootLeft.right = &rootLeftRight;
rootLeftRight.left = &rootLeftRightLeft;
rootRight.right = &rootRightRight;
Solution s;
int result = s.TreeDepth(&root);
return 0;
}
第三次做:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
if ( pRoot == NULL ) return 0 ;
int left = TreeDepth( pRoot->left ) ;
int right = TreeDepth( pRoot->right ) ;
return left > right ? left + 1 : right + 1 ;
}
};