Leetcode Day 3
題目:
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.
二叉樹最長路徑為根節(jié)點到最遠(yuǎn)葉子節(jié)點的節(jié)點個數(shù)。
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
- python
def maxDepth(self,root):
return 1+max(map(self.maxDepth,(root.left, root.right))) if root else 0
- C++
補充一些C++基本知識:
->的含義:- 第一種情況,采用指針訪問 student *xy,則訪問時需要寫成 *xy.name="hhhhh";等價于xy->name="hhhhh";
- 第二種情況,采用普通成員訪問 student xy,則訪問時需要寫成 xy.name="hhhhh";
/**
* 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{
pubilc:
int maxDepth( TreeNode* root){
if (root== NULL)
return 0;
int res =0 ;
quene<TreeNode *> q;
q.push(root); //把root 壓進(jìn) quene q里
while(!q.empty()) // 第一次循環(huán)后,q中不為空,則是被壓入了root的左孩子和右孩子。q不是empty意味著該層不為空。
{
++res;
for ( int i =0, n=q.size(); i<n; ++i)
{
TreeNode *p= q.front(); //front()返回當(dāng)前容器中起始元素的引用。此時第一次返回的是q指向壓進(jìn)去的root
q.pop(); //pop() 移除棧頂元素,此時把quene q 里的root(或重新壓入的元素)扔掉;
if (p->left!=NULL) // 此時指針p指向root, p->left指向 root的左孩子,如果左孩子不為空,則向q中壓進(jìn)左孩子。
q.push(p->left);
if (p->right!=NULL) // 此時指針p指向root, p->right指向 root的右孩子,如果左孩子不為空,則向q中壓進(jìn)右孩子。
q.push(p->right);
}
}
return res;
}
}
C++基本忘光了,每一步都希望寫的很細(xì)致,但可能也有很多錯誤,大家多多指正。