Maximum Depth of Binary Tree
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.
求二叉树的高度,即从根节点到叶节点上所有节点的数量。
解题思路:
这题是难度系数1,频率1的题目……用到的知识点是二叉树DFS(深度遍历)。
一个计数变量count,一个记录最大值变量max。
深度遍历的时候,遍历到的节点分三种情况:
max即为所求的最大深度。
代码如下:
class Solution { public: int maxDepth(TreeNode *root) { int count = 0,max = 0; depth(root,count,max); return max; } void depth(TreeNode *root,int &count,int &max){ if(root){ if(!root->left && !root->right){ count++; if(max < count) max = count; } else{ count++; if(root->left){ depth(root->left,count,max); count--; } if(root->right){ depth(root->right,count,max); count--; } } } } };
难怪难度系数是1,可以简单成这个样子:
class Solution { public: int maxDepth(TreeNode *root) { if(root == NULL) return 0; int l = maxDepth(root->left); int r = maxDepth(root->right); return l > r ? l + 1 : r + 1; } };
【LeetCode练习题】Maximum Depth of Binary Tree,布布扣,bubuko.com
【LeetCode练习题】Maximum Depth of Binary Tree
原文:http://www.cnblogs.com/4everlove/p/3662343.html