Binary Search Tree

Binary Search Tree

Leetcode 98. Validate Binary Search Tree

思路: \color{OrangeRed}思路: 思路: if it’s a valid BST, then using in-order traversal will get an ascending array => use I n − o r d e r \color{OrangeRed}In-order Inorder
R E D O ! ! ! \color{Red} REDO!!! REDO!!!

class Solution {
public:
    TreeNode* prev = nullptr;
    bool isValidBST(TreeNode* root) {
        if (root == nullptr)
        {
            return true;
        }
        bool left_bst = isValidBST(root->left);
        // in order check if the element is from small to large
        if (prev != nullptr && prev->val >= root->val)
        {
            return false;
        }
        prev = root;
        bool right_bst = isValidBST(root->right);
        return left_bst && right_bst;
    }
};

Leetcode 530. Minimum Absolute Difference in BST

思路: \color{OrangeRed}思路: 思路: i n − o r d e r \color{Red} in-order inorder

class Solution:
    def recursive_helper(self, root):
            if root == None:
                return None
            self.recursive_helper(root.left)
            if self.prev != None:
                self.val = min(self.val, root.val - self.prev.val)
            self.prev = root
            self.recursive_helper(root.right)
            
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        self.val = float("inf")
        self.prev = None
        self.recursive_helper(root)
        return self.val

Leetcode 501. Find Mode in Binary Search Tree

class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        self.list = []
        self.prev = None
        self.freq = float("-inf")
        self.cnt = 1
        # use hash_map/hash_set
        # cnt for the most frequent occurence, using inorder traversal
        self.inorder(root)
        return self.list
    
    def inorder(self, root):
        if root != None:
            self.inorder(root.left)
            if self.prev and self.prev.val == root.val:
                self.cnt += 1
            if self.prev and self.prev.val != root.val:
                self.cnt = 1
            self.prev = root
            if self.freq < self.cnt:
                self.freq = self.cnt
                self.list = []
                self.list.append(self.prev.val)
            elif self.freq == self.cnt:
                self.list.append(self.prev.val)
            self.inorder(root.right)

p r e + c u r \color{Red} pre+cur pre+cur

if self.prev == None:
	self.cnt = 1
elif self.prev and self.prev.val == root.val:
	self.cnt += 1
else:
	self.cnt = 1

traverse only once:

if self.freq < self.cnt:
	self.freq = self.cnt
	self.list = []
	self.list.append(self.prev.val)
elif self.freq == self.cnt:
	self.list.append(self.prev.val)

Leetcode 236. Lowest Common Ancestor of a Binary Tree

1. 需要从底向上遍历 = > p o s t o r d e r / b a c k t r a c k i n g \color{Red}1. 需要从底向上遍历 => postorder / backtracking 1.需要从底向上遍历=>postorder/backtracking
R e d o ! ! ! \color{Red}Redo!!! Redo!!!

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root == None or root == p or root == q:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if left and right:
            return root
        elif left == None:
            return right
        return left

Leetcode 235. Lowest Common Ancestor of a BST

  1. use the property of BST
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root == None or root == p or root == q:
            return root
        if root.val > p.val and root.val < q.val:
            return root
        elif root.val < p.val and root.val > q.val:
            return root
        elif root.val > p.val and root.val > q.val:
            return self.lowestCommonAncestor(root.left, p, q)
        return self.lowestCommonAncestor(root.right, p, q) 
  1. iterative method:
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        while root:
            if root.val < p.val and root.val < q.val:
                root = root.right 
            elif root.val > p.val and root.val > q.val:
                root = root.left
            else:
                return root
        return None

Leetcode 701. Insert Into a BST

class Solution {
public:
    TreeNode* parent;
    void helper(TreeNode* root, int val)
    {
        if (root == nullptr)
        {
            if (parent->val < val)
            {
                parent->right = new TreeNode(val);
            }
            else
            {
                parent->left = new TreeNode(val);
            }
            return;
        }
        parent = root;
        if (root->val < val)
        {
            helper(root->right, val);
        }
        else if (root->val > val)
        {
            helper(root->left, val);
        }
        return;
        
    }
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        // recursive
        if (root == nullptr)
        {
            return new TreeNode(val);
        }
        helper(root, val);
        return root;
        // iterative
        /*
        if (root == nullptr)
        {
            return new TreeNode(val);
        }
        TreeNode* ptr = root;
        while (ptr)
        {
            if (ptr->val < val)
            {
                if (ptr->right == nullptr)
                {
                    ptr->right = new TreeNode(val);
                    break;
                }
                ptr = ptr->right;
            }
            else
            {
                if (ptr->left == nullptr)
                {
                    ptr->left = new TreeNode(val);
                    break;
                }
                ptr = ptr->left;
            }
        }
        return root;
        */
    }
};

Leetcode 450. Delete Node in a BST

  TreeNode* deleteNode(TreeNode* root, int key) {
        if (root == nullptr)
        {
            return nullptr;
        }
        // handle if to delete root
        if (root->val == key)
        {
            // delete root
            // the following two if statements also cover when both are none
            // if right child is null
            if (root->right == nullptr)
            {
                TreeNode* left = root->left;
                delete root;
                return left;
            }
            // if left child is null
            if (root->left == nullptr) 
            {
                TreeNode* right = root->right;
                delete root;
                return right;
            }
            // if left and right children are both not null
            TreeNode* left = root->left;
            TreeNode* tmp = root;
            root = root->right;
            delete tmp;
            TreeNode* ptr = root;
            while (ptr->left)
            {
                ptr = ptr->left;
            }
            ptr->left = left;
        }
        else if (root->val > key)
        {
            root->left = deleteNode(root->left, key);
        }
        else if (root->val < key)
        {
            root->right = deleteNode(root->right, key);
        }
        return root;
    }

Leetcode 538. Convert BST to Greater Tree

反中序遍历:累加顺序右中左,用一个 p r e v 存之前的 s u m \color{Red}反中序遍历:累加顺序右中左,用一个prev存之前的sum 反中序遍历:累加顺序右中左,用一个prev存之前的sum

class Solution:
    prev = 0
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root == None:
            return root
        self.convertBST(root.right)
        root.val += self.prev
        self.prev = root.val
        self.convertBST(root.left)
        return root

Leetcode 669. Trim BST

以下代码相当于把节点0(不在范围内)的右孩子节点2(在范围内)返回给上一层:

if (root->val < low) return trimBST(root->right, low, high);

下一代码相当于用节点3的左孩子把下一层返回的节点0的右孩子节点2接住:

root->left = trimBST(root->left, low ,high);
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if (root == nullptr) return nullptr;
        if (root->val < low) return trimBST(root->right, low, high);
        if (root->val > high) return trimBST(root->left, low, high);
        root->left = trimBST(root->left, low ,high);
        root->right = trimBST(root->right, low, high);
        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值