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.
使用递归写比较容易,使用iterative的方法的话需要使用一个队列来进行层次遍历,使用dummy节点来表示一层的结束。注意根节点如果为null的话返回值应该是0,不是null的话至少为1而不是0.
public int maxDepth(TreeNode root) { if(root == null) return 0; return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; }
public int maxDepth(TreeNode root) { Queue<TreeNode> qu = new LinkedList<TreeNode>(); TreeNode dummy = new TreeNode(0); int depth = 0; if(root == null) return depth; qu.offer(root); qu.offer(dummy); depth++; while(qu.size() != 0) { TreeNode temp = qu.poll(); if(temp == dummy && qu.size() != 0) { depth++; qu.offer(dummy); } if(temp.left != null) qu.offer(temp.left); if(temp.right != null) qu.offer(temp.right); } return depth; }
没有评论:
发表评论