一、前言
继续树相关的问题
二、题目
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依沙经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为极的深度。
四、思路
用递归解决,简单直观
五、编码实现
// TreeDepth.h
#pragma once
#include <iostream>
#include "Common.h"
#include "ConstructTree.h"
using namespace std;
#define NAMESPACE_TREEDEPTH namespace NAME_TREEDEPTH {
#define NAMESPACE_TREEDEPTHEND }
template<class T>
int TreeDepth(BinaryTreeNode<T>* pRoot)
{
if (pRoot == nullptr)
{
return 0;
}
return max(TreeDepth(pRoot->m_pLeft) + 1, TreeDepth(pRoot->m_pRight) + 1);
}
//
// 测试开始
NAMESPACE_TREEDEPTH
template<class T>
void test(const char* testName, T* preorder, T* inorder, int length, int expectDepth)
{
BinaryTreeNode<T>* pRoot = ConstructTree(preorder, inorder, length);
int depth = TreeDepth(pRoot);
if (depth == expectDepth)
{
cout << testName << "solution passed." << endl;
}
else
{
cout << testName << "solution failed." << endl;
}
}
// 普通二叉树
// 1
void Test1()
{
const int length = 1;
char preorder[length + 1] = "1";
char inorder[length + 1] = "1";
test("Test1", preorder, inorder, length, 1);
}
// 普通二叉树
// 1
// /
// 2
// /
// 3
// /
// 4
void Test2()
{
const int length = 4;
char preorder[length + 1] = "1234";
char inorder[length + 1] = "4321";
test("Test1", preorder, inorder, length, 4);
}
// 普通二叉树
// 1
// / \
// 2 3
// / / \
// 4 5 6
// \ /
// 7 8
void Test3()
{
const int length = 8;
char preorder[length + 1] = "12473568";
char inorder[length + 1] = "47215386";
test("Test1", preorder, inorder, length, 4);
}
// 完全二叉树
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
void Test4()
{
const int length = 7;
char preorder[length + 1] = "1245367";
char inorder[length + 1] = "4251637";
test("Test2", preorder, inorder, length, 3);
}
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
// / \ / \ / \ / \
// 8 9 10 11 12 13 14 15
void Test5()
{
const int length = 15;
int preorder[length] = { 1, 2, 4, 8, 9, 5, 10, 11, 3, 6, 12, 13, 7, 14, 15 };
int inorder[length] = { 8, 4, 9, 2, 10, 5, 11, 1, 12, 6, 13, 3, 14, 7, 15 };
test("Test3", preorder, inorder, length, 4);
}
NAMESPACE_TREEDEPTHEND
// 测试结束
//
void TreeDepth_Test()
{
NAME_TREEDEPTH::Test1();
NAME_TREEDEPTH::Test2();
NAME_TREEDEPTH::Test3();
NAME_TREEDEPTH::Test4();
NAME_TREEDEPTH::Test5();
}
执行结果: