LeetCode DAY17(654. Maximum Binary Tree&617. Merge Two Binary Trees&700&98)

Preface

This is a new day to continue my binary tree journey.
Learn something new and keep reviewing what I learnt before.

1. Maximum Binary Tree

LeetCode Link: 654. Maximum Binary Tree
You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:

Create a root node whose value is the maximum value in nums.
Recursively build the left subtree on the subarray prefix to the left of the maximum value.
Recursively build the right subtree on the subarray suffix to the right of the maximum value.
Return the maximum binary tree built from nums.

Analysis and Solution

Recursion

LeetCode C++ as followings Recursion

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {//main function with array as parameter and return its pointer
        TreeNode* node = new TreeNode(0);//build a new node to store last leaves node (terminate condition)
        if (nums.size() == 1) {//it is last leaves node
            node->val = nums[0];//import value
            return node;//show the node
        }
        // To find max value and it's index
        int maxValue = 0;
        int maxValueIndex = 0;
        for (int i = 0; i < nums.size(); i++) {//traverse array 
            if (nums[i] > maxValue) {
                maxValue = nums[i];
                maxValueIndex = i;
            }
        }
        node->val = maxValue;
        //  bulid left tree with left elements of max value
        if (maxValueIndex > 0) {
            vector<int> newVec(nums.begin(), nums.begin() + maxValueIndex);//cut the array and build a new array to store left elements
            node->left = constructMaximumBinaryTree(newVec);//recursion
        }
        // bulid right tree with right elements of max value
        if (maxValueIndex < (nums.size() - 1)) {
            vector<int> newVec(nums.begin() + maxValueIndex + 1, nums.end());//cut the array and build a new array to store right elements
            node->right = constructMaximumBinaryTree(newVec);//recursion
        }
        return node;
    }

2. Merge Two Binary Trees

LeetCode Link: 617. Merge Two Binary Trees
You are given two binary trees root1 and root2.

Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

Return the merged tree.

Note: The merging process must start from the root nodes of both trees.

Analysis and Solution

Recursion And Backtrack

LeetCode C++ as followings Recursion And Backtrack

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {//root as parameter,and return new root node
        if (t1 == NULL) return t2; //  t1=null, it's t2 after merged
        if (t2 == NULL) return t1; //  t2=null, it's t1 after merged
        //  modify the value and structure of t1
        t1->val += t2->val;                             // middle
        t1->left = mergeTrees(t1->left, t2->left);      // left tree recursion
        t1->right = mergeTrees(t1->right, t2->right);   // right tree recursion
        return t1;
    }
};

3. Search in a Binary Search Tree

LeetCode Link: 700. Search in a Binary Search Tree
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

Analysis and Solution

Recursion

LeetCode C++ as followings Recursion

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {//root and targetValue as parameters; return the node of targetValue
        if (root == NULL || root->val == val) return root;//terminate conditions
        TreeNode* result = NULL;//return null if couldnot find the targetValue
        if (root->val > val) result = searchBST(root->left, val);//targetValue >rootValue; recursion left tree
        if (root->val < val) result = searchBST(root->right, val);//targetValue <rootValue; recursion right tree
        return result;//show the final tree
    }
};

4.Validate Binary Search Tree

LeetCode Link: 98. Validate Binary Search Tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.

Analysis and Solution

Recursion

LeetCode C++ as followings Recursion

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    vector<int> vec;//build a new array to store node
    void traversal(TreeNode* root) {//recursion inorder, convert tree to array.
        if (root == NULL) return;//remove case0
        traversal(root->left);//recursion left tree
        vec.push_back(root->val); // convert tree to ordered array
        traversal(root->right);//recursion right tree
    }
public:
    bool isValidBST(TreeNode* root) {//judge main function
        vec.clear(); // clear the array
        traversal(root);//recursion root
        for (int i = 1; i < vec.size(); i++) {//traverse array
            // ATTENTION "less than and equal"; No identical elements in a search tree.
            if (vec[i] <= vec[i - 1]) return false;//it should be ordered array after conversion if it is a right binary search tree
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值