标签:
非递归:
public static int maxDepth(TreeNode root){ if(root==null) return 0; Queue<TreeNode> q=new LinkedList<TreeNode>(); q.offer(root); int enQueNum=1; int visitedNum=0; int lastLevNum=1; //做标记 标记到每层最后的节点 当visitedNum与它相等时本层结束 int height=0; while(!q.isEmpty()){ TreeNode now=q.poll(); visitedNum++; if(now.left!=null){ q.offer(now.left); enQueNum++; } if(now.right!=null){ q.offer(now.right); enQueNum++; } if(visitedNum==lastLevNum){ height++; lastLevNum=enQueNum;//lastLevNum的值赋为此时最后进队列的节点数值也是本层的最后节点 } } return height; }
递归:
public static int maxDepth2(TreeNode root){ if(root==null) return 0; int leftHeight=0; int rightHeight=0; leftHeight=maxDepth2(root.left); rightHeight=maxDepth2(root.right); return leftHeight>rightHeight?leftHeight+1:rightHeight+1; }
Maximum Depth of Binary Tree-求二叉树高度
标签:
原文地址:http://www.cnblogs.com/hhhhh/p/4597165.html