第一类回溯,求值或判断,不修改二叉树结构,如求二叉树深度或判断是否是平衡二叉树
struct TreeNode{
char c;
TreeNode* left;
TreeNode* right;
};
int GetDepth(TreeNode* root)
{
if(root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1;
int leftDepth = GetDepth(root->left);
int rightDepth = GetDepth(root->right);
return leftDepth > rightDepth : (leftDepth + 1) : (rightDepth + 1);
}
bool IsBalance(TreeNode* root, int & depth)
{
if(root == NULL)
{
depth = 0;
return true;
}
if(root->left == NULL && root->right == NULL)
{
depth = 1;
return true;
}
int leftDepth;
int rightDepth;
bool leftBalance = IsBalance(root->left, leftDepth);
if(leftBalance)
bool rightBalance = IsBalance(root->right, rightDepth);
if(rightBalance)
return leftDepth - rightDepth == 1 || rightDepth - leftDepth == 1;
return false;
}
第二类问题需将当前状态以参数形式传入递归函数,如路径和问题
给定一个二叉树和一个值,判断是否存在从根到叶子节点的路径和等于给定值
bool ExistPath(TreeNode* root, int sum)
{
if(root == NULL)
return false;
if(root->left == NULL && root->right == NULL)
if(root->value == sum)
return true;
return ExistPath(root->left, sum-root->value) || ExistPath(root->right, sum-root->value);
}
给定一个二叉树和一个值,打印出所有从根到叶子节点路径和等于该值的路径
用一个全局栈保存当前路径
void AllPath(TreeNode* root, int sum)
{
if(root == NULL)
return;
stack.push(root->value);
if(root->left == NULL && root->right == NULL && root->value == sum)
print stack;
if(sum>root->value)
{
AllPath(root->left, sum-root->value);
AllPath(root->right, sum-root->value);
}
stack.pop();
}
第二类问题需修改二叉树结构,如将二叉搜索树转化为双向链表