110. Balanced Binary Tree
110. Balanced Binary Tree I had this subproblems all written down. But didn’t’t Know how to group them together into code 2.The second method is based on DFS. Instead of calling depth() explicitly for each child node, we return the height of the current node in DFS recursion. When the sub tree of the current node (inclusive) is balanced, the function dfsHeight() returns a non-negative value as the height. Otherwise -1 is returned. According to the leftHeight and rightHeight of the two children, the parent node could check if the sub tree class Solution { public boolean isBalanced(TreeNode root) { return dfs(root) != -1; } private int dfs(TreeNode root){ if(root == null) return 0; int left = dfs(root.left); if(left == -1) return -1; // if left subtree is not balanced , return - 1; otherwise it returns a positive number or 0. int right = dfs(root.right); if(right == -1) return -1; // if right subtree is not balanced, return -1; otherwise it returns a positive number or 0. if(Math.abs(left - right) > 1) return -1; // if the right subtree and left subtree depth difference is more than 1, return - 1 return Math.max(left, right) + 1; // this returns the depth from a root node , which takes the max(left subtree depth, right subtree depth) + 1 } } This -1 means false, not balanced
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
posted on 2018-08-09 17:12 猪猪🐷 阅读(94) 评论(0) 收藏 举报
浙公网安备 33010602011771号