1、当使用带有返回值得递归时,适用于返回值能代表确切含义的情况。
int getDepth(TreeNode *root){
if(root) return 0;
int left = getDepth(root->left);
int right = getDepth(root->right);
return 1 + max(left, right);
}
int getDepth(TreeNode *root){
if(root){
return 1+max(getDepth(root->left),getDepth(root->right));
}
return 0;
}
void getDepth(TreeNode *root, int &dept){
if(!root) {dept=0;return; }
int left, right;
getDepth(root->left, left);
getDepth(root->right, right);
dept = 1 + max(left, right);
}
2、适合求递归中间符合的条件值,求中序遍历的第k个节点,无法划分左右子树递归直接返回,只能定义全局变量标记。
void preOrder(TreeNode* proot, int &ans)
{
if(proot){
preOrder(proot->left, ans);
if(--K == 0) ans=proot->val;
preOrder(proot->right, ans);
}
}
void preOrder(TreeNode* proot, int &ans)
{
if(!proot) return;
preOrder(proot->left, ans);
if(--K == 0) ans=proot->val;
preOrder(proot->right, ans);
}