二叉树的递归框架

1、二叉树框架
void traverse(TreeNode root) {// root 需要做什么?在这做。
    // 其他的不用 root 操心,抛给框架traverse(root.left);
    traverse(root.right);
}
<1>把二叉树所有的节点中的值加一
void plusOne(TreeNode root) {
    if (root == null) return;
    root.val += 1;
    plusOne(root.left);
    plusOne(root.right);
}
<2> 如何判断两棵二叉树是否完全相同
boolean isSameTree(TreeNode root1, TreeNode root2) {
    // 都为空的话,显然相同
    if (root1 == null && root2 == null) return true;
    // 一个为空,一个非空,显然不同
    if (root1 == null || root2 == null) return false;
    // 两个都非空,但 val 不一样也不行
    if (root1.val != root2.val) return false;

    // root1 和 root2 该比的都比完了
    return isSameTree(root1.left, root2.left)
        && isSameTree(root1.right, root2.right);
}
2、BST框架
 // Time:O(H);Space:O(H)
void BST(TreeNode root, int target) {
    if (root.val == target)// 找到目标,做点什么】
        
    if (root.val < target) 
        BST(root.right, target);
    if (root.val > target)
        BST(root.left, target);
}
(1)BST的搜索
    TreeNode* searchBST(TreeNode* root, int val) {
        if(nullptr == root) return NULL;
        if(root->val == val) return root;
        return root->val > val?searchBST(root->left,val):searchBST(root->right,val); 
    }
(2)BST插入
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(nullptr == root) return new TreeNode(val);
        if(root->val > val){
            root->left = insertIntoBST(root->left,val);
        }else{
            root->right = insertIntoBST(root->right,val);
        }
        return root;
    }
(3)BST删除
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(root == nullptr) return root;
        if(root->val < key) root->right = deleteNode(root->right,key);
        else if(root->val > key) root->left = deleteNode(root->left,key);
        else{ // 删除当前节点
            // 没有左右子树
            if(nullptr == root->left && nullptr == root->right){
                return nullptr;
            }
            // 没有左子树,有右子树
            if(nullptr == root->left && nullptr != root->right){
                return root->right;
            }
            // 没有右子树,有左子树
            if(nullptr == root->right && nullptr != root->left){
                return root->left;
            }
            // 有左右子树
            if(nullptr != root->left && nullptr != root->right){
                TreeNode* node = root->right;
                while(nullptr != node->left){
                    node = node->left;
                }
                node->left = root->left;
                root = root->right;
            }
        }
        return root;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值