【LeetCode】Maximum Depth of Binary Tree

来源:互联网 发布:ubuntu 17.04 wine qq 编辑:程序博客网 时间:2024/05/17 22:39

参考:

队列法参考:http://www.2cto.com/kf/201312/263115.html

题目描述


http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/

Maximum Depth of Binary Tree

 

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.



题目分析

就是给出一个棵树,给出最大深度

使用递归比较简单。求出左、右树的最大高度,然后取最大值加1就是根的最大高度


循环法——栈:麻烦一些,跟后序遍历的循环法相似,需要记录上一个被遍历的结点。
循环法目前只用后序的方法解决了,但先序和中序暂时还没有解决。暂时没想到方法,如果有人知道欢迎讨论。



循环法——队列:这个是参考网上代码,这个思路确实不错,需要学习的是如果标记一层遍历结束。

总结

一个出错的地方。记录上一个结点的变量preNode的初始值不应该是NULL,应该是root

代码示例




class Solution {public:    int maxDepth(TreeNode *root) {        if(root == NULL)    return 0;                return max(maxDepth(root->left),maxDepth(root->right))+1;////////////////加1    }    };



推荐学习C++的资料

C++标准函数库
http://download.csdn.net/detail/chinasnowwolf/7108919
在线C++API查询
http://www.cplusplus.com/

0 0
原创粉丝点击