博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[c][算法]二叉树的深度
阅读量:6241 次
发布时间:2019-06-22

本文共 2328 字,大约阅读时间需要 7 分钟。

hot3.png

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

/*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 *//** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */// class Solution {// public://     int maxDepth(TreeNode* root) {       //     }// };
#import 
#import
typedef struct TreeNode TreeNode;struct TreeNode { int val; TreeNode *left; TreeNode *right; // TreeNode(int x) : val(x), left(NULL), right(NULL) {}};TreeNode* MakeTreeNode(int x);void ConnectTreeNodes(TreeNode* pParent,TreeNode* pLeft,TreeNode* pRight);int maxDepth(TreeNode* root);int main (int argc, const char * argv[]){ @autoreleasepool { // TEST // 1 // / \ // 2 3 // /\ \ // 4 5 6 // / // 7 //creat Nodes TreeNode* pNode1 = MakeTreeNode(1); TreeNode* pNode2 = MakeTreeNode(2); TreeNode* pNode3 = MakeTreeNode(3); TreeNode* pNode4 = MakeTreeNode(4); TreeNode* pNode5 = MakeTreeNode(5); TreeNode* pNode6 = MakeTreeNode(6); TreeNode* pNode7 = MakeTreeNode(7); //connect Nodes ConnectTreeNodes(pNode1, pNode2, pNode3); ConnectTreeNodes(pNode2, pNode4, pNode5); ConnectTreeNodes(pNode3, NULL, pNode6); ConnectTreeNodes(pNode5, pNode7, NULL ); int depth = maxDepth(pNode1); NSLog(@"maxDepth is %d", depth); }}TreeNode* MakeTreeNode(int x){ TreeNode *node = malloc(sizeof(TreeNode)); node->val = x; node->left = NULL; node->right = NULL; return node;}void ConnectTreeNodes(TreeNode* pParent,TreeNode* pLeft,TreeNode* pRight){ if(pParent!=NULL) { pParent->left = pLeft; pParent->right = pRight; }}int maxDepth(TreeNode* root) { return root==NULL?0:1+MAX(maxDepth(root->left),maxDepth(root->right));}

转载于:https://my.oschina.net/u/1993252/blog/861020

你可能感兴趣的文章
Hadoop学习笔记(九)HDFS架构分析
查看>>
DB2数据库常用基本操作命令
查看>>
RHEL5.8安装Sybase 15.7_x86_64
查看>>
函数适配器bind2nd 、mem_fun_ref 源码分析、函数适配器应用举例
查看>>
武汉科技大学ACM :1002: A+B for Input-Output Practice (II)
查看>>
extjs中form.reset(true)出现的bug修复
查看>>
Some Android functions
查看>>
ORB-SLAM2学习4 initializer.h
查看>>
正向代理和反向代理
查看>>
1092 回文字符串(LCSL_DP)
查看>>
day01-Python介绍,安装,idea
查看>>
AX函数,将EXCEL列号转为列名
查看>>
UNDO -- Concept
查看>>
养生《一》
查看>>
es6的模块化--AMD/CMD/commonJS/ES6
查看>>
DevStack部署Openstack环境
查看>>
新年最新的100句超牛的语言(转)
查看>>
Chromium Graphics: Graphics and Skia
查看>>
asp.net core mvc上传大文件解决方案
查看>>
二叉树
查看>>