遞歸的執行順序
一直以來都沒有在意過遞歸的執行順序,當有一天刷劍指offer時看答案看不懂,在代碼的方法中第三行,遞歸本方法。思路就徹底亂了,到底誰前誰後。直接扔代碼:
public class Solution {
private TreeNode pre;
private TreeNode head;
public TreeNode Convert(TreeNode pRootOfTree) {
inorder(pRootOfTree);
return head;
}
private void inorder(TreeNode P)
{
if(P== null)
return;
inorder(P.left);
if(head==null)
{
head = P;
pre = P;
}
else
{
pre.right = P;
P.left = pre;
pre = P;
}
inorder(P.right);
}
}
```java
在inorder方法中,inorder(P.left);
相當於inorder(P.left);
inorder(P.left.left);
直到後面爲空爲止。
而且是需要等inorder(P.left)執行完之後,才能繼續往下執行。