一、深度
遞歸版本
public static int getDeep(TreeNode root){ if(root == null) return 0; int left = getDeep(root.left); int right = getDeep(root.right); return 1 + Math.max(left, right); }
非遞歸版本
思想:二叉樹的深度就是指二叉樹有幾層,那么我們可以使用層序遍歷來實現。
public static int getDeep(TreeNode root) { if(root == null) return 0; LinkedList<TreeNode> list = new LinkedList<>(); list.add(root); int count = 1; //每層的結點數 int level = 1; //層數 while(!list.isEmpty()) { int size = 0; //臨時保存下層的結點數 for(int i = 0; i < count; i++) { TreeNode p = list.removeFirst(); if(p.left != null) { size++; list.addLast(p.left); } if(p.right != null) { size++; list.addLast(p.right); } } //如果下一層沒有結點,則結束循環 if(size == 0) break; count = size; level++; } return level; }
二、寬度
思想:二叉樹的寬度就是最寬的那一層的節點數,所以還是需要層序遍歷的思想,先計算每層的結點數,然后找出最大的。
public static int getWidth(TreeNode root) { if(root == null) return 0; LinkedList<TreeNode> list = new LinkedList<>(); list.add(root); int count = 1; //每層的結點數 int width = 1; //寬度 while(!list.isEmpty()) { int size = 0; //臨時保存下層的結點數 for(int i = 0; i < count; i++) { TreeNode p = list.removeFirst(); if(p.left != null) { size++; list.addLast(p.left); } if(p.right != null) { size++; list.addLast(p.right); } } if(size == 0) break; //如果下一層沒有結點,則結束循環 if(size > width) width = size; count = size; } return width; }