leetcode Maximum Depth of Binary python C++
来源:互联网 发布:app软件产品说明书 编辑:程序博客网 时间:2024/05/29 04:15
又来刷下限了。都是很easy的题目。求轻喷~
就是求二叉树的高度问题。
首先想到的就是递归,递归代码超简单啊。
直接上代码:
# Definition for a binary tree node# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # @param root, a tree node # @return an integer def maxDepth(self, root): if None == root: return 0 else: leftDep = self.maxDepth(root.left)+1 rightDep = self.maxDepth(root.right)+1 if leftDep > rightDep: return leftDep else: return rightDep
搞定!
自己又想写个不是递归的,怎能奈何10来分钟都没有思路。只能百度一下了。
啊,一看别人的代码。就是广度遍历不就好了。哎,还是太嫩了。这么简单的问题。
如下链接是原文:C++版
害怕丢失了,特记录在此:
class Solution {public: //二叉树最大深度(层次遍历,遍历一层高度加1) int maxDepth(TreeNode *root) { int height = 0,rowCount = 1; if(root == NULL){ return 0; } //创建队列 queue<treenode*> queue; //添加根节点 queue.push(root); //层次遍历 while(!queue.empty()){ //队列头元素 TreeNode *node = queue.front(); //出队列 queue.pop(); //一层的元素个数减1,一层遍历完高度加1 rowCount --; if(node->left){ queue.push(node->left); } if(node->right){ queue.push(node->right); } //一层遍历完 if(rowCount == 0){ //高度加1 height++; //下一层元素个数 rowCount = queue.size(); } } return height; } };自己还是太欠缺,慢慢来吧。多看多思考。老大说我做事有时候应该多思考,看来是没错啊。find the best way to do it
0 0
- leetcode-Maximum Depth of Binary Tree-python
- leetcode Maximum Depth of Binary python C++
- 【Leetcode】【python】Maximum Depth of Binary Tree
- [C]LeetCode:Maximum Depth of Binary Tree
- 【LeetCode with Python】 Maximum Depth of Binary Tree
- 【LeetCode】【Python题解】Single Number & Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth Of Binary Tree Python 题解
- [leetcode: Python]104. Maximum Depth of Binary Tree
- [C++]LeetCode: 29 Maximum Depth of Binary Tree
- 【leetcode c++】104 Maximum Depth of Binary Tree
- [leetcode-104]Maximum Depth of Binary Tree(c)
- LeetCode 104. Maximum Depth of Binary Tree C语言
- Leetcode-104. Maximum Depth of Binary Tree c语言
- LeetCode 104. Maximum Depth of Binary Tree 题解(C++)
- LeetCode 104. Maximum Depth of Binary Tree (C++)
- [LeetCode] [C] 104. Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- [Leetcode] Maximum Depth of Binary Tree
- VS2010(C#)工程调试时报源文件和模块文件不匹配的错的解决办法
- 关于typedef的用法总结
- Android入门之Fragment用法
- poj3294 Life Forms
- 磁盘被写保护怎样去掉
- leetcode Maximum Depth of Binary python C++
- linux 编译选项中加入-shared 造成执行程序coredump
- matlab图片,矩阵,函数的基本用法
- 循环链表
- ubuntu 使用
- 快速排序算法
- php get_post 提交
- [转载论文]蚁群算法在最优路径上的应用
- The final local variable xxx cannot be assigned, since it is defined in an enclosing type“,