104. 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.
题目大意:
给一个二叉树,找出最大深度。
最大深度是沿着从根节点到最远叶节点的最长路径的节点数。
C++
/**
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) {
//采用DFS的思想
if(root == NULL)
return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;
}
};
注意:
- 参考链接 DFS BFS
- http://www.cnblogs.com/bakari/p/4126693.html
- http://blog.youkuaiyun.com/wangyaninglm/article/details/45700837
- 理解递归定义,理解二叉树结构
- ->是指向运算符,其作用与成员运算符(.)是一样的,只不过在它左边的名字不是实例,而是指针。依然用类A。
A *p = new A;
p->foo(); //调用类A的指针变量p指向的实例的成员函数foo
p->number = 0; //调用类A的指针变量p指向的实例的成员变量number赋值
delete p; //释放指针
p = null; //将指针置空
A *p则使用:p->play(); 左边是结构指针。
A p 则使用:p.paly(); 左边是结构变量。
总结:
箭头(->):左边必须为指针;
点号(.):左边必须为实体。