Balanced Binary Tree
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.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { if (root == null) return true; if (getHeight(root) != -1) return true; return false; } public int getHeight(TreeNode root){ if (root == null) return 0; int left_height = getHeight(root.left); int right_height = getHeight(root.right); if (left_height == -1 || right_height == -1) return -1; if (Math.abs(left_height - right_height) > 1) return -1; return Math.max(left_height, right_height) + 1; } }
Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
I did not figure how to do this fisrtly. Then I read some solution and figure it as recursive solution. I did not think about iterative solution this time.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) return true; return isSymmetric(root.left, root.right); } public boolean isSymmetric(TreeNode left, TreeNode right){ if (left == null && right == null) return true; else if (left == null || right == null) return false; else if (left.val != right.val) return false; else if (!isSymmetric(left.left, right.right)) return false; else if (!isSymmetric(left.right, right.left)) return false; return true; } }