stack

1:
recoverTree(TreeNode root) {
……
swap(first, second);
}

public void swap(TreeNode a, TreeNode b){
if(a==null || b==null) return;
int temp = a.val;
a.val=b.val;
b.val=temp;
}
2. recoverTree(TreeNode root) {
……
if(first!=null || second!=null)
swap(first, second);
}

public void swap(TreeNode a, TreeNode b){
int temp = a.val;
a.val=b.val;
b.val=temp;
}

the only difference between 1 and 2 is the place of checking null for first and second

but way 1 times out.

why?

I think it is because the return address of the swap method use memory. If swap is used many time, then it might cause a problem.

https://myrubylearning.wordpress.com/2013/06/14/recursion-pointers-use-stack-memory/

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s