104. Maximum Depth of Binary Tree

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.

  1. python
def maxDepth(self,root):
   return 1+max(map(self.maxDepth,(root.left, root.right))) if root else 0
  1. C++
    補充一些C++基本知識:
    ->的含義:
    1. 第一種情況,采用指針訪問 student *xy,則訪問時需要寫成 *xy.name="hhhhh";等價于xy->name="hhhhh";
    2. 第二種情況,采用普通成員訪問 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ì)致,但可能也有很多錯誤,大家多多指正。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容