回溯问题(一)二叉树相关

第一类回溯,求值或判断,不修改二叉树结构,如求二叉树深度或判断是否是平衡二叉树


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();
}



第二类问题需修改二叉树结构,如将二叉搜索树转化为双向链表



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值