題目描述
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹,
解題思路
在做這題是,我第一反應就是遍歷兩次二叉樹,第一遍記錄每個節點的深度,并將資訊存入HashMap中,key = node,value = https://www.cnblogs.com/iamxiaoye/p/depth,第二遍再遍歷一次二叉樹,同時判斷每個節點是不是都是平衡二叉樹,但這個方法并不是最優的,沒有進行剪枝,增加了不少不必要的開銷,而且使用了更多的額外空間,
1 private HashMap<TreeNode, Integer> nodeDepth = new HashMap<>(); 2 private boolean flag = true; 3 4 public boolean IsBalanced_Solution(TreeNode root) { 5 if (root == null) { 6 return true; 7 } 8 if (flag) { 9 depth(root); 10 flag = false; 11 } 12 int depthLeft = nodeDepth.get(root.left) == null ? -1 : nodeDepth.get(root.left) ; 13 int depthRight = nodeDepth.get(root.right) == null ? -1 : nodeDepth.get(root.right) ; 14 return Math.abs(depthLeft - depthRight) < 2 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right); 15 } 16 17 public int depth(TreeNode node) { 18 if (node == null) return -1; 19 int d = Math.max(depth(node.left), depth(node.right)) + 1; 20 nodeDepth.put(node, d); 21 return d; 22 }
在提交完代碼后,我看到解題思路分享里有一個更棒的方法,作者是丁滿歷險記,他的方法從下往上遍歷,如果子樹是平衡二叉樹,則回傳子樹的高度;如果發現子樹不是平衡二叉樹,則直接停止遍歷,這樣至多只對每個結點訪問一次,
1 public boolean IsBalanced_Solution(TreeNode root) { 2 return getDepth(root) != -1; 3 } 4 5 public int getDepth(TreeNode node) { 6 if (node == null) return 0; 7 int left = getDepth(node.left); 8 if (left == -1) return -1; 9 int right = getDepth(node.right); 10 if (right == -1) return -1; 11 return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1; 12 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/116933.html
標籤:其他
上一篇:netty即使通信
