分享

104   leetcode - Maximum Depth of Binary Tree 

 雪柳花明 2016-09-25

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.
题目很简单,但考的很基础。二叉树的遍历方式有两种:递归和非递归,本题也有两种解法。


本题为查询树的深度,我们采用直接遍历二叉树,并记录我们访问深度的方法即可。

可以考虑用一个全局变量记录我们的深度,也可以通过DFS函数每一次返回当前子树的深度。

若采用返回值,则有

当前树长度 = max(左子树深度, 右子树深度) + 1



计算二叉树的深度,简单的前序遍历即可。
递归算法:

点击(此处)折叠或打开

  1. /**
  2.  * Definition for binary tree
  3.  * public class TreeNode {
  4.  * int val;
  5.  * TreeNode left;
  6.  * TreeNode right;
  7.  * TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10. public class Solution {
  11.     public int maxDepth(TreeNode root) {
  12.         int depth = 0;
  13.         if(root != null){
  14.             int leftDepth = maxDepth(root.left);
  15.             int rightDepth = maxDepth(root.right);
  16.             depth ++;
  17.             if(leftDepth < rightDepth){
  18.                 depth = depth + rightDepth;
  19.             }else{
  20.                 depth = depth + leftDepth;
  21.             }
  22.         }
  23.         return depth;
  24.     }
  25. }
非递归算法:
受后续遍历二叉树思想的启发,想到可以利用后续遍历的方法来求二叉树的深度,在每一次输出的地方替换成算栈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,结束遍历

点击(此处)折叠或打开

  1. int TreeDeep(BinTree BT ){
  2.     int treedeep=0;
  3.     stack S;
  4.     stack tag;
  5.     BinTree p=BT;
  6.     while(p!=NULL||!isEmpty(S)){
  7.         while(p!=NULL){
  8.             push(S,p);
  9.             push(tag,0);
  10.             p=p->lchild;
  11.         }
  12.         if(Top(tag)==1){
  13.             deeptree=deeptree>S.length?deeptree:S.length;
  14.             pop(S);
  15.             pop(tag);
  16.             p=NULL;
  17.         }else{
  18.             p=Top(S);
  19.             p=p->rchild;
  20.             pop(tag);
  21.             push(tag,1);
  22.         }
  23.     }
  24.     return deeptree;
  25. }
前序、中序、和后序遍历的递归和非递归实现,参考博文:
http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多