zoukankan      html  css  js  c++  java
  • 二叉搜索树(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;
        }
    };
  • 相关阅读:
    每日日报7月15日
    每日日报7月14日
    ecplise下 java问题处理
    Visual Studio Code for .Net Framework
    Go语言操作MySQL数据库
    Go语言Gin-4中间件
    Go语言Gin-2.数据传输
    Go语言Gin-1.路由
    13.Go语言-并发编程
    12.Go语言-网络编程
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11384715.html
Copyright © 2011-2022 走看看