[leetcode]110BalancedBinaryTree平衡二叉樹
阿新 • • 發佈:2018-01-25
判斷 開始 help 如果 二叉 bsp body nod pos
public boolean isBalanced(TreeNode root) { int res = helper(root); if (res<0) return false; return true; } public int helper(TreeNode root) { if (root==null) return 0; //從底下開始判斷是否平衡樹 //兩個變量如果是-1就代表是不平衡 int ld = helper(root.left);int rd = helper(root.right); //三種情況就不平衡:左右子樹不平衡,本節點不平衡 if (ld==-1||rd==-1||Math.abs(ld-rd)>1) return -1; else if (ld>rd) return ld+1; else return rd+1; }
[leetcode]110BalancedBinaryTree平衡二叉樹