• 二叉搜索树(BST)


     

    删除二叉搜索树的某一结点时,若是叶子结点直接删掉;否则,将该结点的右子树的最左结点来代替该结点。

    661. Convert BST to Greater Tree

    思路: 递归遍历二叉树的右,根,左。用sum来统计每个结点的前缀和。

    /** 
     * Definition for a binary tree node. 
     * struct TreeNode { 
     *     int val; 
     *     TreeNode *left; 
     *     TreeNode *right; 
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
     * }; 
     */  
    class Solution {  
    public:  
    int sum;  
      
    void dfs(TreeNode* cur){  
        //右,中,左遍历  
        if(cur == NULL) return;  
        dfs(cur->right);   
        sum += cur->val;  
        cur->val = sum;  
        dfs(cur->left);  
    }  
      
        TreeNode* convertBST(TreeNode* root) {  
            sum = 0;   //统计前缀和  
            dfs(root);  
            return root;  
        }  
    };  

    649. Binary Tree Upside Down

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    
    class Solution {
    public:
        /**
         * @param root: the root of binary tree
         * @return: new root
         */
        TreeNode* newRoot;
        
        void dfs(TreeNode* cur){
            if(cur->left == NULL){
                newRoot = cur;
                return;
            }
            dfs(cur->left);
            cur->left->left = cur->right;
            cur->left->right = cur;  
            cur->left = NULL;
            cur->right = NULL;
        }
        
        TreeNode * upsideDownBinaryTree(TreeNode * root) {
            // write your code here
            if(root == NULL) return root;
            dfs(root);
            return newRoot;
        }
    };
  • 相关阅读:
    CentOs7-替换下载源
    CentOs7-常用命令
    Django Nginx+uwsgi 安装配置
    Linux操作系统下文件作用
    U盘创建macOS安装盘
    国内开源镜像站点汇总
    gcd常见用法
    mac rvm 升级 ruby 安装cocoapod 指定版本
    confluence 搭建 wiki 并破解
    homebrew 安装 java 指定版本
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11384715.html
Copyright © 2020-2023  润新知