Leetcode 104. Maximum Depth of Binary Tree
2016-05-24 09:04
295 查看
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) {} * }; */ int maxDepth(TreeNode *root) { return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1; }
方法二:广度优先搜索,非递归,容易理解
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; }
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- 一波二叉树遍历问题的C++解答实例分享
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- PHP实现的线索二叉树及二叉树遍历方法详解
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++将二叉树转为双向链表及判断两个链表是否相交
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- C++实现查找二叉树中和为某一值的所有路径的示例
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)
- JavaScript数据结构和算法之二叉树详解