104. Maximum Depth of Binary Tree 求树的最大深度
来源:互联网 发布:赫德森太太知乎 编辑:程序博客网 时间:2024/06/05 00:23
1,my solution
/** * 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 ans; int maxDepth(TreeNode* root) { help(root, 1); return ans; } void help(TreeNode* root, int depht){ if(root == NULL) return; ans = max(ans, depht); help(root->left, depht + 1); help(root->right, depht + 1); }};
2,another solution
int maxDepth(TreeNode* root) { if(root == NULL){ return 0; } int depth_left = maxDepth(root->left) + 1; int depth_right = maxDepth(root->right) + 1; return depth_left > depth_right ? depth_left : depth_right;}
- Depth-first-search
======
Only one line code.
int maxDepth(TreeNode *root){ return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;}
- Breadth-first-search
======
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 求树的最大深度
- Tree-----求树的最大深度和最小深度(104. Maximum Depth of Binary Tree 111. Minimum Depth of Binary Tree)
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- Maximum Depth of Binary Tree 二叉树的最大深度
- maximum-depth-of-binary-tree(二叉树的最大深度)
- 求二叉树的最大深度 Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree (求二叉树的最大深度 C语言)
- leetcode系列(28)Maximum Depth of Binary Tree 求二叉树的最大深度
- Maximum Depth of Binary Tree --- 求二叉树的最大深度
- LeetCode OJ-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 | 二叉树的深度
- 【LeetCode】Maximum Depth of Binary Tree (二叉树最大深度)
- Leetcode Maximum Depth of Binary Tree 二叉树最大深度
- 四、管道命令的使用
- Intelij IDEA2016中常用技巧(插件、主题、快捷键等)
- Android 文件存储系统
- nodejs mongoose 操作mongodb 数据库封装
- 彩笔笔记2016/12/6——collection
- 104. Maximum Depth of Binary Tree 求树的最大深度
- Paxos算法与Zookeeper分析
- •算法分析中常见的复杂度
- 五类IP地址范围及作用
- 五.如何用批处理文件来操作注册表
- windows错误事件10016解决方案
- 19. Remove Nth Node From End of List leetcode list
- 大数相乘
- Remove Duplicates from Sorted Array