JZ38-二叉树深度
二叉树的深度
http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b
- BFS层序遍历:
import java.util.List; import java.util.LinkedList; public class Solution { public int TreeDepth(TreeNode root) { if(root == null) return 0; List<TreeNode> queue = new LinkedList<>(); queue.add(root); List<TreeNode> tmp; int res = 0; while(!queue.isEmpty()) { tmp = new LinkedList<>(); for(TreeNode node : queue) { if(node.left != null) tmp.add(node.left); if(node.right != null) tmp.add(node.right); } queue = tmp; res++; } return res; } }
- DFS深度优先遍历(实际上是后续遍历)
public class Solution { public int TreeDepth(TreeNode root) { if(root == null) return 0; int lval = TreeDepth(root.left); int rval = TreeDepth(root.right); return Math.max(lval , rval) + 1; } }