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.
二叉树最长路径为根节点到最远叶子节点的节点个数。
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 压进 quene q里
        while(!q.empty())   // 第一次循环后,q中不为空,则是被压入了root的左孩子和右孩子。q不是empty意味着该层不为空。
         {
            ++res;
            for ( int i =0, n=q.size(); i<n; ++i)
            {
                TreeNode *p= q.front(); //front()返回当前容器中起始元素的引用。此时第一次返回的是q指向压进去的root
                q.pop();                 //pop() 移除栈顶元素,此时把quene q 里的root(或重新压入的元素)扔掉;
                
                 if (p->left!=NULL)   // 此时指针p指向root, p->left指向 root的左孩子,如果左孩子不为空,则向q中压进左孩子。
                        q.push(p->left);
                 if (p->right!=NULL) // 此时指针p指向root, p->right指向 root的右孩子,如果左孩子不为空,则向q中压进右孩子。
                        q.push(p->right);

}
}
                return res;

}
}

C++基本忘光了,每一步都希望写的很细致,但可能也有很多错误,大家多多指正。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容