Why Stack Overflow Error for this code?


  • 0
    E

    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);
    	height(root);
    	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;
    	if(map.containsKey(root.left))
    	    heightLeft = map.get(root.left);
    	else {
    	    heightLeft = height(root.left);
    	    map.put(root.left, heightLeft);
    	}
    	if(map.containsKey(root.right)) 
    	    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.