I traverse the tree and transfer it into an array.Then compare the two arrays.Is that right?


  • 0
    S

    I traverse the tree in the pre order,and put every node I visit in an array.If I visit a null node,then I put a MIN_VALUE in the array then return and continue until all the nodes are done.
    At last I compare these two arrays.
    Why does my solution return true when it comes across two different trees like {10,5,15} and {10,5,#,#,15}?

    And what does {10,5,15} or {10,5,#,#,15} exactly mean?

    public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        ArrayList<Integer> buf = new ArrayList<Integer>();
    	ArrayList<Integer> buf2 = new ArrayList<Integer>();
    	PreOrderTraverse(buf, p);
    	PreOrderTraverse(buf2, q);
    	if(buf.size()!=buf2.size()){
    		return false;
    	}
    	else{
    		for(int i=0;i<buf.size();i++){
    			if(buf.indexOf(i)!=buf2.indexOf(i)){
    				return false;
    			}
    		}
    	}
    	return true;
    }
    
    public void PreOrderTraverse(ArrayList<Integer> buf,TreeNode t){
        if(t==null){
            buf.add(Integer.MIN_VALUE);
            return;
        }
    	buf.add(t.val);
    	PreOrderTraverse(buf, t.left);
    	PreOrderTraverse(buf, t.right);
    }
    

    }


Log in to reply
 

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