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));}