给各位一个非递归的傻办法:
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.*; public class Solution { //思路:用一个全新的数据结构,其中包括原树的节点和其的深度值,用队列广度遍历,找到最大那个值即可 public class TreeNodeBfs{//新数据结构,新增了节点的深度 TreeNode root; int depth; public TreeNodeBfs(TreeNode root1,int depth1){ this.depth = depth1; this.root = root1; } } public int TreeDepth(TreeNode root){ if(root == null){//空树则返回0 return 0; } TreeNodeBfs rootNew = new TreeNodeBfs(root,1); return BfsDepth(rootNew); } public int BfsDepth(TreeNodeBfs root){ Queue queue = new LinkedList(); queue.offer(root);//根节点入队列 int maxDepth = 1; while(queue.size()!=0){//只要队列仍然有内容,将左&右入队,左&右的深度为当前的深度+1,将当前的出队 if(queue.peek().root.left!=null){ int newDepth = queue.peek().depth+1; queue.offer(new TreeNodeBfs(queue.peek().root.left,newDepth)); } if(queue.peek().root.right!=null){ int newDepth = queue.peek().depth+1; queue.offer(new TreeNodeBfs(queue.peek().root.right,newDepth)); } if(queue.peek().depth>maxDepth){ maxDepth = queue.peek().depth; } queue.poll(); } return maxDepth; } }