Leetcode: Maximum Depth of Binary Tree
2015-11-14 21:18
411 查看
题目:算出二叉树的最大深度
解决方案:(1)BFS (2)DFS
(1)BFS
一层一层往下搜索,一直找到最深的点,这里由于节点的val是没有用的,所以可以用来存储当前节点的深度,然后注意指针一定要初始化,不然在leetcode里可能会出现runtime error/** * 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 maxDepth(TreeNode* root) { if(!root) return 0; list<TreeNode*> node_list; node_list.push_back(root); root->val=1; int maxe=1; while (node_list.size() != 0) { TreeNode* now_node=NULL;//指针需要初始化 now_node = node_list.front(); node_list.pop_front(); if (now_node->left != NULL) { node_list.push_back(now_node->left); now_node->left->val=now_node->val+1; if(now_node->left->val>maxe)maxe=now_node->left->val; } if (now_node->right != NULL) { node_list.push_back(now_node->right); now_node->right->val=now_node->val+1; if(now_node->right->val>maxe)maxe=now_node->right->val; } } return maxe; } };
(2) DFS
用递归的方法来写该题的程序,代码会很简洁/** * 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 maxDepth(TreeNode* root) { if(!root) return 0; int leftmax=0, rightmax=0; leftmax=maxDepth(root->left); rightmax=maxDepth(root->right); if(leftmax>rightmax) return leftmax+1; else return rightmax+1; } };
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- C++非递归队列实现二叉树的广度优先遍历
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)
- JavaScript数据结构和算法之二叉树详解
- java使用归并删除法删除二叉树中节点的方法
- Java中二叉树数据结构的实现示例
- python数据结构之二叉树的建立实例
- python数据结构树和二叉树简介
- python数据结构之二叉树的统计与转换实例