二叉搜索树(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;
    }
};

 

posted @ 2019-11-27 14:58  爱学英语的程序媛  阅读(182)  评论(0编辑  收藏  举报