104. Maximum Depth of Binary Tree Add to List DescriptionHintsSubmissions
来源:互联网 发布:淘宝3个月没卖出一件 编辑:程序博客网 时间:2024/05/16 18:04
题目
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.
翻译
给定一个二叉树,找到其最大深度。
最大深度是从根节点到最远叶节点的最长路径中的节点数。
分析
之前在刷链表的时候有过类似的题,也是递归的方法
思索片刻后写出了如下代码
/** * 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 buildmax(TreeNode* root,int m){ if(root==NULL) return m; if(root->left==NULL||root->right==NULL) return m+1; m=max(m,buildmax(root->left,m+1),buildmax(root->right,m+1)); return m; } int maxDepth(TreeNode* root) { int x=buildmax(root,0); return x; }};
查询后才知道max min函数不能直接对三个使用,
错误示范:max(a,b,c),
正确示范:max(a,max(b,c)).
然后去答案区学习大神的代码后,男默女泪
Only one line code.
int maxDepth(TreeNode *root){ return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;}
后附带大神的最大宽度代码Calculate the count of the last level.
int maxDepth(TreeNode *root){ if(root == NULL) return 0; int res = 0; queue<TreeNode *> q; q.push(root); while(!q.empty()) { ++ res; for(int i = 0, n = q.size(); i < n; ++ i) { TreeNode *p = q.front(); q.pop(); if(p -> left != NULL) q.push(p -> left); if(p -> right != NULL) q.push(p -> right); } } return res;}
0 0
- 104. Maximum Depth of Binary Tree Add to List DescriptionHintsSubmissions
- 104.Maximum Depth of Binary Tree Add to List
- leetcode104~Maximum Depth of Binary Tree Add to List
- Add to List 111. Minimum Depth of Binary Tree
- [LeetCode]104.Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 【LeetCode】104.Maximum Depth of Binary Tree
- [Leetcode] 104. Maximum Depth of Binary Tree
- LeetCode --- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- leetCode 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree LeetCode
- LeetCode | 21. Merge Two Sorted Lists
- oj2325查找【数组】
- java 去英文单词出现的次数
- 1407: [Noi2002]Savage
- hdu1242优先队列+BFS
- 104. Maximum Depth of Binary Tree Add to List DescriptionHintsSubmissions
- jquery.pagination.js分页的使用
- Python 编程遇到的一些小问题 新手勿喷,嘻嘻
- java-创建线程
- linux makefile教程
- Android 对话框
- pin planner中符号标记的含义
- JDK1.8十个新特性
- KMP之Next数组