Why Stack Overflow Error for this code?

  • 0

    I know this algorithm is not right for this problem, but I don't understand why it gives me a stack over flow error.

    public class Solution {
    private HashMap<TreeNode, Integer> map;
    public boolean isBalanced(TreeNode root) {
    	if(root == null) return true;
    	map = new HashMap<>();
    	map.put(null, 0);
    	if(Math.abs(map.get(root.left) - map.get(root.right)) > 1) return false;
    	return true;
    private int height(TreeNode root) {
    	if(root == null) return 0;
    	int heightLeft, heightRight;
    	    heightLeft = map.get(root.left);
    	else {
    	    heightLeft = height(root.left);
    	    map.put(root.left, heightLeft);
    	    heightRight = map.get(root.right);
    	else {
    	    heightRight = height(root.right);
    	    map.put(root.right, heightRight);
    	return 1+Math.max(heightLeft, heightRight);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.