题目简介
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.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
int left=0;
int right=0;
if(root==null)
return 0;
else{
left=maxDepth(root.left);
right=maxDepth(root.right);
if(left>=right)
return left+1;
else
return right+1;
}
}
}
刚看完了题目,就想到了递归的思想。如果当前节点为空,返回0。分别计算左子树和右子树的深度,比较一下,输出最大的。
Hot解法
- /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) { - if(root==null){
- return 0;
- }
- return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
- }
- }
Hot解法的思路基本上和我一样都是递归的方法,只不过是在代码上又做了优化
其实递归的方法,都可以用栈来实现非递归,因为栈其实就可以模拟递归的过程。这道题目如果用非递归算法的话,麻烦的一点就是还需要保存每个子树的深度。
非递归算法的代码 转载自http://blog.csdn.net/zqt520/article/details/8036407
非递归实现基本思想:
受后续遍历二叉树思想的启发,想到可以利用后续遍历的方法来求二叉树的深度,在每一次输出的地方替换成算栈S的大小,遍历结束后最大的栈S长度即是栈的深度。
算法的执行步骤如下:
(1)当树非空时,将指针p指向根节点,p为当前节点指针。
(2)将p压入栈S中,0压入栈tag中,并令p执行其左孩子。
(3)重复步骤(2),直到p为空。
(4)如果tag栈中的栈顶元素为1,跳至步骤(6)。从右子树返回
(5)如果tag栈中的栈顶元素为0,跳至步骤(7)。从左子树返回
(6)比较treedeep与栈的深度,取较大的赋给treedeep,对栈S和栈tag出栈操作,p指向NULL,并跳至步骤(8)。
(7)将p指向栈S栈顶元素的右孩子,弹出栈tag,并把1压入栈tag。(另外一种方法,直接修改栈tag栈顶的值为1也可以)
(8)循环(2)~(7),直到栈为空并且p为空
(9)返回treedeep,结束遍历
- int TreeDeep(BinTree BT ){
- int treedeep=0;
- stack S;
- stack tag;
- BinTree p=BT;
- while(p!=NULL||!isEmpty(S)){
- while(p!=NULL){
- push(S,p);
- push(tag,0);
- p=p->lchild;
- }
- if(Top(tag)==1){
- deeptree=deeptree>S.length?deeptree:S.length;
- pop(S);
- pop(tag);
- p=NULL;
- }else{
- p=Top(S);
- p=p->rchild;
- pop(tag);
- push(tag,1);
- }
- }
- return deeptree;
- }
= =非递归的逻辑上不太好理解,自己动手走几遍就明白了