其他分享
首页 > 其他分享> > 代码随想录-二叉树

代码随想录-二叉树

作者:互联网

#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <unordered_map>

using namespace std;

struct TreeNode
{
    int val = 0;
    TreeNode* left = nullptr;
    TreeNode* right = nullptr;
    TreeNode* next = nullptr;
    TreeNode(int val_):val(val_),left(nullptr),right(nullptr),next(nullptr) 
    {
        ;
    }
};

void print(const vector<vector<int>>& nums)
{
    for(auto vs:nums)
    {
        for(auto num : vs)
        {
            cout << num << " ";
        }
        cout << endl;
    }
}

template<typename T>
void print(const vector<T>nums)
{
    for(T num : nums)
    {
        cout << num << " "; 
    }
    cout << endl;
}

void pre(TreeNode* node, vector<int>& vec)
{
    if(nullptr == node)return;
    vec.push_back(node->val);
    pre(node->left,vec);
    pre(node->right,vec);
}

void in(TreeNode* node, vector<int>& vec)
{
    if(nullptr == node)return;    
    in(node->left,vec);
    vec.push_back(node->val);
    in(node->right,vec);
}

void post(TreeNode* node, vector<int>& vec)
{
    if(nullptr == node)return;    
    post(node->left,vec);
    post(node->right,vec);
    vec.push_back(node->val);
}

vector<int>pre(TreeNode* node)
{
    vector<int>res;
    if(nullptr == node)return res;
    stack<TreeNode*>st;
    st.push(node);
    while(!st.empty())
    {
        TreeNode* cur = st.top();
        st.pop();
        res.push_back(cur->val);
        if(cur->right)st.push(cur->right);
        if(cur->left)st.push(cur->left);
    }
    return res;
}

vector<int>in(TreeNode* node)
{
    vector<int>res;
    stack<TreeNode*>st;
    TreeNode* cur = node;
    while(cur != nullptr || !st.empty())
    {
        if(cur != nullptr)
        {
            st.push(cur);
            cur = cur->left;
        }
        else
        {
            cur = st.top();
            st.pop();
            res.push_back(cur->val);
            cur = cur->right;
        }
    }
    return res;

}

vector<int>post(TreeNode* node)
{
    vector<int>res;
    if(nullptr == node)return res;
    stack<TreeNode*>st;
    st.push(node);
    while(!st.empty())
    {
        TreeNode* cur = st.top();
        st.pop();
        res.push_back(cur->val);
        if(cur->left != nullptr)st.push(cur->left);
        if(cur->right != nullptr)st.push(cur->right);
    }
    reverse(res.begin(),res.end());
    return res;    
}

vector<int>visit(TreeNode* node)
{
    vector<int>res;
    pre(node,res);
    // res = pre(node);
    
    // in(node,res);
    // res = in(node);
    
    // post(node,res);
    // res = post(node);
    return res;
}

vector<vector<int>> levelOrder(TreeNode* node)
{
    vector<vector<int>>res;
    if(nullptr == node)return res;
    queue<TreeNode*>q;
    q.push(node);
    while (!q.empty())
    {
        int size = q.size();
        vector<int>v;
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();
            q.pop();            
            v.push_back(cur->val);
            if(cur->left != nullptr)q.push(cur->left);
            if(cur->right != nullptr)q.push(cur->right);
        }
        res.push_back(v);
    }
    return res;
    
}

vector<vector<int>>levelOrderII(TreeNode* node)
{
    vector<vector<int>>res;
    if(nullptr == node)return res;
    queue<TreeNode*>q;
    q.push(node);
    while(!q.empty())
    {
        int size = q.size();
        vector<int>v;
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();
            q.pop();
            v.push_back(cur->val);
            if(cur->left != nullptr)q.push(cur->left);
            if(cur->right != nullptr)q.push(cur->right);
        }
        res.push_back(v);
    }
    reverse(res.begin(),res.end());
    return res;
}

vector<int>rightSideView(TreeNode* node)
{
    vector<int>res;
    if(nullptr == node)return res;
    queue<TreeNode*>q;
    q.push(node);
    while(!q.empty())
    {
        int size = q.size();
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();
            q.pop();
            if(i == size - 1)
            {
                res.push_back(cur->val);
            }
            if(cur->left != nullptr)q.push(cur->left);
            if(cur->right != nullptr)q.push(cur->right);
        }            
    }
    return res;
}

vector<double> averageofLevels(TreeNode* node)
{
    vector<double>res;
    if(nullptr == node)return res;
    queue<TreeNode*>q;
    q.push(node);
    while(!q.empty())
    {
        int size = q.size();
        double sum = 0.;
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();
            q.pop();
            sum += cur->val;
            if(cur->left != nullptr)q.push(cur->left);
            if(cur->right != nullptr)q.push(cur->right);
        }        
        res.push_back(sum / size);
    }    
    return res;
}

vector<int>largestVals(TreeNode* node)
{
    vector<int>res;
    if(nullptr == node)
    return res;
    queue<TreeNode*>q;
    q.push(node);
    while(!q.empty())
    {
        int size = q.size();
        int maxVal = INT_MIN;
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();
            q.pop();
            maxVal = max(maxVal,cur->val);
            if(cur->left)q.push(cur->left);
            if(cur->right)q.push(cur->right);            
        }
        res.push_back(maxVal);
    }
    return res;
}

TreeNode* connect(TreeNode* node)
{
    if(node == nullptr)return nullptr;
    queue<TreeNode*>q;    
    q.push(node);
    while(!q.empty()){
        TreeNode* cur,*preNode;
        int size = q.size();
        for(int i = 0; i < size; ++i)
        {
            if(0 == i)
            {
                preNode = q.front();
                q.pop();
                cur = preNode;
            }
            else
            {
                cur = q.front();
                q.pop();
                preNode->next = cur;
                preNode = preNode->next;
            }
            if(cur->left != nullptr)q.push(cur->left);
            if(cur->right != nullptr)q.push(cur->right);
        }
        cur->next=nullptr;
    }
    return node;
}

TreeNode* invertTree(TreeNode* node)
{
    if(nullptr == node)return nullptr;
    swap(node->left,node->right);
    invertTree(node->left);
    invertTree(node->right);
    return node;
}

TreeNode* dfs_invertTree(TreeNode* node)
{
    if(nullptr == node)return nullptr;
    stack<TreeNode*>st;
    st.push(node);
    while(!st.empty())
    {
        TreeNode* cur = st.top();
        st.pop();
        swap(cur->left,cur->right);
        if(cur->right != nullptr)st.push(cur->right);
        if(cur->left != nullptr)st.push(cur->left);
    } 
    return node;
}

TreeNode* bfs_invertTree(TreeNode* node)
{
    if(nullptr == node)return nullptr;
    queue<TreeNode*>q;
    q.push(node);
    while (!q.empty())
    {
        int size = q.size();
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();
            q.pop();
            swap(cur->left,cur->right);
            if(cur->left != nullptr)q.push(cur->left);
            if(cur->right != nullptr)q.push(cur->right);
        }
    }
    return node;
    
}

bool compare(TreeNode* left, TreeNode* right)
{
    if(nullptr == left && nullptr != right)return false;
    else if(nullptr == right && nullptr != left)return false;
    else if(nullptr == left && nullptr == right)return true;
    else if(left->val != right->val)return false;
    bool outside = compare(left->left,right->right);
    bool inside = compare(left->right,right->left);
    return inside && outside;
    
}

bool isSymmetric(TreeNode* root)
{
    if(root == nullptr)return true;
    return compare(root->left,root->right);
}

bool isSymmetric_queue(TreeNode* root)
{
    if(root == nullptr)return true;
    queue<TreeNode*>q;
    q.push(root->left);
    q.push(root->right);
    while(!q.empty())
    {
        TreeNode* leftNode = q.front();q.pop();
        TreeNode* rightNode = q.front();q.pop();
        if(!leftNode && !rightNode)continue;
        if(!leftNode || !rightNode || (leftNode->val != rightNode->val))
        return false;
        q.push(leftNode->left);
        q.push(rightNode->right);
        q.push(leftNode->right);
        q.push(rightNode->left);
    }
    return true;
}

bool isSymmetric_stack(TreeNode* root)
{
    if(nullptr == root)return true;
    stack<TreeNode*>st;
    st.push(root->left);
    st.push(root->right);
    while(!st.empty())
    {
        TreeNode* leftNode = st.top();st.pop();
        TreeNode* rightNode = st.top();st.pop();
        if(!leftNode && !rightNode)continue;
        if(!leftNode || !rightNode || leftNode->val != rightNode->val)return false;
        st.push(leftNode->left);
        st.push(rightNode->right);
        st.push(leftNode->right);
        st.push(rightNode->left);
    }
    return true;
}

int getDepth(TreeNode* root)
{
    if(nullptr == root)
    return 0;
    int leftDepth = getDepth(root->left);
    int rightDepth = getDepth(root->right);
    return 1 + max(leftDepth,rightDepth);
}

int getDepth_q(TreeNode* root)
{
    if(nullptr == root)return 0;
    queue<TreeNode*>q;
    q.push(root);
    int depth = 0;
    while(!q.empty())
    {
        int size = q.size();
        ++depth;
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();
            q.pop();
            if(cur->left != nullptr)q.push(cur->left);
            if(cur->right != nullptr)q.push(cur->right);
        }
        
    }
    return depth;
}

int getMinDepth(TreeNode* root)
{
    if(nullptr == root)return 0;
    int leftDepth = getMinDepth(root->left);
    int rightDepth = getMinDepth(root->right);
    if(root->left == nullptr && root->right!=nullptr)
    {
        return 1 + rightDepth;
    }
    if(root->right == nullptr && root->left != nullptr)
    {
        return 1 + leftDepth;
    }
    return 1 + min(leftDepth,rightDepth);
}

int getMinDepth_q(TreeNode* root)
{
    if(nullptr == root)return 0;
    queue<TreeNode*>q;
    q.push(root);
    int depth = 0;
    while(!q.empty())
    {
        int size = q.size();
        ++depth;
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();q.pop();
            if(cur->left != nullptr)q.push(cur->left);
            if(cur->right != nullptr)q.push(cur->right);
            if(cur->left == nullptr && cur->right == nullptr)
            {
                return depth;
            }
        }
    }
    return depth;
}

int getCountNums(TreeNode* root)
{
    if(nullptr == root)return 0;
    int leftNums = getCountNums(root->left);
    int rightNums = getCountNums(root->right);
    return 1 + leftNums + rightNums;
}

int getCountNums_q(TreeNode* root)
{
    if(nullptr == root)return 0;
    queue<TreeNode*>q;
    q.push(root);
    int res = 0;
    while(!q.empty())
    {
        int size = q.size();
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur  = q.front();q.pop();
            ++res;
            if(cur->left)q.push(cur->left);
            if(cur->right)q.push(cur->right);            
        }
    }
    return res;
}

int getDepth_help(TreeNode* root)
{
    if(nullptr == root)return 0;
    int left = getDepth_help(root->left);
    if(left == -1)return -1;
    int right = getDepth_help(root->right);
    if(right == -1)return -1;
    return abs(left-right) > 1 ? -1 : 1 + max(left,right);
}

bool isBalance(TreeNode* root)
{
    return getDepth_help(root) == -1 ? false : true;
}

void travelsal(TreeNode* node,vector<int>& path,vector<string>& res)
{
    path.push_back(node->val);
    if(node->left==nullptr && node->right==nullptr)
    {
        string sPath = "";
        for(int i = 0; i < path.size() - 1; ++i)
        {
            sPath += to_string(path[i]);
            sPath += "->";
        }
        sPath += to_string(path[path.size() - 1]);
        res.emplace_back(sPath);
        return;
    }
    if(node->left)
    {
        travelsal(node->left,path,res);
        path.pop_back();
    }
    if(node->right)
    {
        travelsal(node->right,path,res);
        path.pop_back();
    }    
}

vector<string>binaryTreePath(TreeNode* root)
{
    vector<string>res;
    vector<int>path;
    travelsal(root,path,res);
    return res;

}

vector<string>binaryTreePaths(TreeNode* root)
{
    vector<string>res;
    if(root == nullptr)return res;
    stack<TreeNode*>st;
    stack<string>paths;
    st.push(root);
    paths.push(to_string(root->val));
    while(!st.empty())
    {
        TreeNode* cur = st.top();st.pop();
        string path = paths.top();paths.pop();
        if(cur->left == nullptr && cur->right == nullptr)res.emplace_back(path);
        if(cur->right)
        {
            st.push(cur->right);
            paths.push(path + "->" +to_string(cur->right->val));
        }
        if(cur->left)
        {
            st.push(cur->left);
            paths.push(path + "->"+to_string(cur->left->val));
        }
    }
    return res;
}

int sumOfLeftLeaves(TreeNode* root)
{
    if(nullptr == root)return 0;
    int leftSum = sumOfLeftLeaves(root->left);
    int rightSum = sumOfLeftLeaves(root->right);
    int midVal = 0;
    if(root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr)
    midVal = root->left->val;
    return midVal + leftSum + rightSum;
}

int sumOfLeftLeaves_st(TreeNode* root)
{
    if(nullptr == root)return 0;
    stack<TreeNode*>st;
    st.push(root);
    int res = 0;
    while(!st.empty())
    {
        TreeNode* cur = st.top();st.pop();
        if(cur->left != nullptr && cur->left->left == nullptr && cur->left->right == nullptr)
        {
            res += cur->left->val;
        }        
        if(cur->right)
        {
            st.push(cur->right);
        }
        if(cur->left)
        {
            st.push(cur->left);            
        }
    }
    return res;
}

int findBottomLeftVal(TreeNode* root)
{
    if(nullptr == root)return 0;
    queue<TreeNode*>q;
    int res = 0;
    q.push(root);
    while (!q.empty())
    {
        int size = q.size();
        for(int i = 0 ; i < size; ++i)
        {
            TreeNode* cur = q.front();q.pop();
            if(0 == i)res = cur->val;
            if(cur->left)q.push(cur->left);
            if(cur->right)q.push(cur->right);
        }
    }
    return res;
    
}

bool traversal(TreeNode* root, int target)
{
    if(root->left == nullptr && root->right == nullptr && target == 0)return true;
    if(root->left == nullptr && root->right == nullptr)return false;
    if(root->left)
    {
        target -= root->left->val;
        if(traversal(root->left,target))return true;
        target += root->left->val;
    }
    if(root->right)
    {
        target -= root->right->val;
        if(traversal(root->right,target))return true;
        target += root->right->val;
    }
    return false;
}

bool hasPathSum(TreeNode* root,int target)
{
    if(nullptr == root)
    return false;
    return traversal(root,target - root->val);
}

bool hasPathSum_st(TreeNode* root, int target)
{
    if(nullptr == root)return false;
    stack<pair<TreeNode*,int>>st;
    st.push({root,root->val});
    while(!st.empty())
    {
        auto node = st.top();st.pop();
        if(!node.first->left && !node.first->right && node.second == target)return true;
        if(node.first->right != nullptr)
        {
            st.push({node.first->right,node.second + node.first->right->val});
        }
        if(node.first->left != nullptr)
        {
            st.push({node.first->left,node.second + node.first->left->val});
        }
    }
    return false;
}

void travelsal(TreeNode* root,vector<int>& path,vector<vector<int>>& res,int target)
{    
    if(root->left == nullptr && root->right == nullptr && target == 0)
    {
        res.push_back(path);        
        return;
    }
    if(root->left == nullptr && root->right == nullptr)
    {
        return ;
    }
    if(root->left)
    {
        path.push_back(root->left->val);
        target -= root->left->val;
        travelsal(root->left,path,res,target);
        target += root->left->val;
        path.pop_back();
    }
    if(root->right)
    {
        path.push_back(root->right->val);
        target -= root->right->val;
        travelsal(root->right,path,res,target);
        target += root->right->val;
        path.pop_back();
    }    
    return ;
}

vector<vector<int>>pathSum(TreeNode* root,int target)
{
    vector<vector<int>>res;
    if(nullptr == root)return res;
    vector<int>path;
    path.push_back(root->val);
    travelsal(root,path,res,target - root->val);        
    return res;
}

TreeNode* build(vector<int>&inorder,vector<int>&postorder)
{
    if(postorder.size() == 0)return nullptr;
    int rootVal = postorder[postorder.size() - 1];
    TreeNode* root = new TreeNode(rootVal);
    if(postorder.size() == 1)return root;
    int index = 0;
    for(; index < inorder.size(); ++index)
    {
        if(inorder[index] == rootVal)
        {
            break;
        }
    }
    vector<int>leftInorder{inorder.begin(),inorder.begin() + index};
    vector<int>rightInorder{inorder.begin() + index + 1,inorder.end()};
    postorder.resize(postorder.size() - 1);
    vector<int>leftPostorder{postorder.begin(),postorder.begin() + leftInorder.size()};
    vector<int>rightPostorder{postorder.begin() + leftInorder.size(),postorder.end()};
    root->left = build(leftInorder,leftPostorder);
    root->right = build(rightInorder,rightPostorder);
    return root;    
}

TreeNode* buildTreeNode(vector<int>&inorder,vector<int>&postorder)
{
    if(inorder.size() == 0 || postorder.size() == 0)return nullptr;
    return build(inorder,postorder);
}

TreeNode* build(vector<int>&preorder,int preBeg,int preEnd,vector<int>&inorder,int inBeg,int inEnd)
{
    if(preBeg == preEnd)return nullptr;
    int rootVal = preorder[preBeg];
    TreeNode* root = new TreeNode(rootVal);
    if(preEnd - preBeg == 1) return root;
    int index = 0;
    for(index = inBeg; index < inEnd; ++ index)
    {
        if(inorder[index] == rootVal)
        {
            break;
        }
    }
    
    int leftInorderBeg = inBeg;
    int leftInorderEnd = index;
    int rightInorderBeg = index + 1;
    int rightInorderEnd = inEnd;

    int leftPreorderBeg = preBeg + 1;
    int leftPreorderEnd = preBeg + 1 + index - inBeg;
    int rightPreorderBeg = preBeg + 1 + index - inBeg;
    int rightPreorderEnd = preEnd;
    root->left = build(preorder,leftPreorderBeg,leftPreorderEnd,inorder,leftInorderBeg,leftInorderEnd);    
    root->right = build(preorder,rightPreorderBeg,rightInorderEnd,inorder,rightInorderBeg,rightInorderEnd);
    return root;
}

TreeNode* buildTreeNodeII(vector<int>&preorder,vector<int>&inorder)
{
    if(preorder.size() == 0 || inorder.size() == 0)
    {
        return nullptr;
    }    
    return build(preorder,0,preorder.size(),inorder,0,inorder.size());
}

TreeNode* constructMaxBinaryTree(const vector<int>& nums)
{
    TreeNode* node = new TreeNode(0);
    if(nums.size() == 1)
    {
        node->val = nums[0];
        return node;
    }
    int maxIndex = 0;
    int maxVal = *max_element(nums.begin(),nums.end());
    for(int i = 0; i < nums.size(); ++i)
    {
        if(nums[i] == maxVal)
        {
            maxIndex = i;
            break;
        }
    }
    node->val = maxVal;
    if(maxIndex > 0)
    {
        vector<int>vecN{nums.begin(),nums.begin() + maxIndex};
        node->left = constructMaxBinaryTree(vecN);
    }
    if(maxIndex < nums.size() - 1)
    {
        vector<int>vecN{nums.begin()+maxIndex+1,nums.end()};
        node->right = constructMaxBinaryTree(vecN);
    }
    return node;
}

TreeNode* mergeTree(TreeNode* t1, TreeNode* t2)
{
    if(nullptr == t1)return t2;
    if(nullptr == t2)return t1;
    t1->val += t2->val;
    t1->left = mergeTree(t1->left,t2->left);
    t1->right = mergeTree(t1->right,t2->right);
    return t1;

}

TreeNode* mergeTree_q(TreeNode* t1, TreeNode* t2)
{
    if(nullptr == t1)return t2;
    if(nullptr == t2)return t1;
    queue<TreeNode*>q;
    q.push(t1);
    q.push(t2);
    while(!q.empty())
    {
        TreeNode* n1 = q.front();q.pop();
        TreeNode* n2 = q.front();q.pop();
        n1->val += n2->val;
        if(n1->left != nullptr && n2->left != nullptr)
        {
            q.push(n1->left);
            q.push(n2->left);
        }
        if(n1->right != nullptr && n2->right != nullptr)
        {
            q.push(n1->right);
            q.push(n2->right);
        }
        if(n1->left == nullptr && n2->left != nullptr)
        {
            n1->left = n2->left;
        }
        if(n1->right == nullptr && n2->right != nullptr)
        {
            n1->right = n2->right;
        }        
    } 
    return t1;
}

TreeNode* searchBST(TreeNode* root, int val)
{
    if(nullptr == root || root->val == val)return root;
    if(root->val > val)return searchBST(root->left,val);
    if(root->val < val)return searchBST(root->right,val);
    return nullptr;        
}

TreeNode* searchBST_iter(TreeNode* root,int val)
{
    while(root!=nullptr)
    {
        if(root->val > val)root = root->left;
        else if(root->val < val) root = root->right;
        else return root;
    }
    return nullptr; 
}

int maxV = INT_MIN;
bool isValidBST(TreeNode* root)
{
    if(nullptr == root)return true;
    bool left = isValidBST(root->left);
    if(maxV < root->val) maxV = root->val;
    bool right = isValidBST(root->right);
    return left && right;
}

bool isValidBST_st(TreeNode* root)
{
    stack<TreeNode*>st;
    TreeNode* pre = nullptr;
    TreeNode* cur = root;
    while(cur != nullptr || !st.empty())
    {
        if(cur != nullptr)
        {
            st.push(cur);
            cur = cur->left;
        }
        else
        {
            cur = st.top();st.pop();
            if(pre != nullptr && pre->val >= cur->val)return false;
            pre = cur;
            cur = cur->right;
        }
    }
    return true;
}

void minTravelsal(TreeNode* node,TreeNode* pre,vector<int>&res)
{
    if(nullptr == node)return;
    minTravelsal(node->left,pre,res);
    if(pre != nullptr)
    {
        res[0] = min(res[0],node->val - pre->val);
    }
    pre = node;
    minTravelsal(node->right,pre,res);

}

int getMinDiff(TreeNode* node)
{
    vector<int>res{INT_MAX};
    minTravelsal(node,nullptr,res);
    return res[0];
}

int getMinDiff_st(TreeNode* node)
{
    if(nullptr == node)return 0;
    stack<TreeNode*>st;
    TreeNode* cur = node;
    TreeNode* pre = nullptr;
    int res = INT_MAX;
    while(cur != nullptr || !st.empty())
    {
        if(cur != nullptr)
        {
            st.push(cur);
            cur = cur->left;
        }
        else
        {
            cur = st.top();st.pop();
            if(pre != nullptr)res = min(res,cur->val - pre->val);
            pre = cur;
            cur = cur->right;
        }
    }
    return res;
}

void travelsal(TreeNode* node, unordered_map<int,int>& map)
{
    if(nullptr == node)return ;
    ++map[node->val];
    travelsal(node->left,map);
    travelsal(node->right,map);

}

vector<int>findMode(TreeNode* node)
{
    vector<int>res;
    if(nullptr == node)return res;
    unordered_map<int,int>map;
    travelsal(node,map);
    vector<pair<int,int>>v{map.begin(),map.end()};
    sort(v.begin(),v.end(),[](const pair<int,int>&a,const pair<int,int>&b){return a.second > b.second;});
    res.push_back(v[0].first);
    for(int i = 1; i < v.size(); ++i)
    {
        if(v[i].second == v[0].second)
        {
            res.push_back(v[i].first);
        }
    }    
    return res;
}

vector<int>findMode_st(TreeNode* node)
{
    stack<TreeNode*>st;
    TreeNode* cur = node;
    TreeNode* pre = nullptr;
    vector<int>res;
    int cnt = 0, maxCnt = INT_MIN;
    while(cur != nullptr || !st.empty())
    {
        if(cur != nullptr)
        {
            st.push(cur);
            cur = cur->left;
        }
        else
        {
            cur = st.top();st.pop();
            if(pre == nullptr)cnt = 1;
            else if(pre->val == cur->val)++cnt;
            else cnt = 1;
            if(cnt == maxCnt)
            {
                res.push_back(cur->val);                
            }
            if(cnt > maxCnt)
            {
                maxCnt = cnt;
                res.clear();
                res.push_back(cur->val);
            }
            pre = cur;
            cur = cur->right;
        }
        
    }
    return res;    
}

TreeNode* lowestCommonTree(TreeNode* node,TreeNode* p, TreeNode* q)
{
    if(node == nullptr || node == p || node == q)return node;
    TreeNode* left = lowestCommonTree(node->left,p,q);
    TreeNode* right = lowestCommonTree(node->right,p,q);
    if(left != nullptr && right != nullptr)return node;
    else if(left != nullptr && right == nullptr)return left;
    else if(left == nullptr && right != nullptr )return right;
    else return nullptr;
}

TreeNode* lowestCommonTreeII(TreeNode* node,TreeNode* p, TreeNode* q)
{
    if(node == nullptr || node == p || node == q)return node;
    if(node->val > p->val && node->val > q->val)
    {
        TreeNode* left = lowestCommonTreeII(node->left,p,q);
        if(left != nullptr)return left;
    }    
    if(node->val < p->val && node->val < q->val)
    {
        TreeNode* right = lowestCommonTreeII(node->right,p,q);
        if(right != nullptr)return right;
    }    
    return node;
}

TreeNode* lowestCommonTreeII_iter(TreeNode* node,TreeNode* p, TreeNode* q)
{
    if(node == nullptr || node == p || node == q)return node;
    while(node)
    {
        if(node->val > p->val && node->val >q->val)
        {
            node = node->left;
        }
        else if(node->val < p->val && node->val < q->val)
        {
            node = node->right;
        }
        else 
        return node;
    }
    return nullptr;    
}

TreeNode* insertIntoBST(TreeNode* root, int val)
{
    if(nullptr == root){
        TreeNode* node = new TreeNode(val);
        return node;
    }
    root->left = insertIntoBST(root->left,val);
    root->right = insertIntoBST(root->right,val);
    return root;
}

TreeNode* insertIntoBST_iter(TreeNode* root,int val)
{
    if(nullptr == root)
    {
        TreeNode* node = new TreeNode(val);
        return node;
    }
    TreeNode* cur = root;
    TreeNode* pre = nullptr;
    while(cur != nullptr)
    {
        pre = cur ;
        if(cur->val > val)cur = cur->left;
        else cur = cur->right;
    }
    TreeNode* node = new TreeNode(val);
    if(val < pre->val)pre->left = node;
    else pre->right = node;
    return root;
}

TreeNode* deleteNode(TreeNode* root, int key)
{
    if(nullptr == root)return root;
    if(root->val == key)
    {
        if(root->left == nullptr) return root->right;
        else if(root->right == nullptr) return root->left;
        else
        {
            TreeNode* cur = root->right;
            while (cur->left != nullptr)            
            {
                cur = cur->left;
            }
            cur->left = root->left;
            TreeNode* tmp = root;
            cur->left = tmp;
            root = root->right;
            delete tmp;
            return root;            
        }
    }
    if(root->val > key)root->left = deleteNode(root->left,key);
    if(root->val < key)root->right = deleteNode(root->right,key);
    return root;
}

TreeNode* deleteOneNode(TreeNode* target)
{
    if(nullptr == target)return target;
    if(target->right == nullptr)return target->left;
    TreeNode* cur = target->right;
    while(cur->left)
    {
        cur = cur->left;
    }
    cur->left = target->left;
    return target->right;
}

TreeNode* deleteNode_iter(TreeNode* root,int key)
{
    if(nullptr == root)return root;
    TreeNode* cur = root;
    TreeNode* pre = nullptr;
    while(cur)
    {
        if(cur->val == key)break;
        pre = cur;
        if(cur->val > key)cur = cur->left;
        else cur = cur->right;
    }
    if(nullptr == pre)
    {
        return deleteOneNode(cur);
    }
    if(pre->left && pre->left->val == key)
    {
        pre->left = deleteOneNode(cur);
    }
    if(pre->right && pre->right->val ==key)
    {
        pre->right = deleteOneNode(cur);
    }
    return root;
}

TreeNode* trimTree(TreeNode* root, int low ,int high)
{
    if(nullptr == root)return nullptr;
    if(root->val < low)
    {
        TreeNode* right = trimTree(root->right,low,high);
        return right;
    }
    
    if(root->val > high)
    {
        TreeNode* left = trimTree(root->left,low,high);
        return left;
    }
    root->left = trimTree(root->left,low,high);
    root->right = trimTree(root->right,low,high);
    return root;
}

TreeNode* trimTreeNode_iter(TreeNode* root,int L ,int H)
{
    if(nullptr == root)return nullptr;
    if(root->val < L || root->val > H)
    {
        if(root->val < L)root = root->right;
        else root = root->left;
    }
    TreeNode* cur = root;
    while(cur != nullptr)
    {
        while(cur->left != nullptr && cur->left->val < L)
        {
            cur->left = cur->left->right;
        }
        cur = cur->left;
    }
    cur = root;
    while(cur != nullptr)
    {
        while(cur->right != nullptr && cur->right->val > H)
        {
            cur->right = cur->right->left;
        }
        cur = cur->right;
    }
    return root;
}

TreeNode* travel(const vector<int>&nums,int left, int right)
{
    if(left > right) return nullptr;
    int mid = left + (right - left) / 2;
    TreeNode* root = new TreeNode(nums[mid]);
    root->left = travel(nums,left,mid - 1);
    root->right = travel(nums,mid + 1,right);
    return root;
}

TreeNode* sortedAtoBST(const vector<int>& nums)
{
    return travel(nums,0,nums.size() - 1);
}

TreeNode* sortedAtoBST_q(const vector<int>& nums)
{
    if(nums.size() == 0)return nullptr;
    TreeNode* root = new TreeNode(0);
    queue<TreeNode*>q;
    queue<int>leftq,rightq;
    q.push(root);
    leftq.push(0);
    rightq.push(nums.size() - 1);
    while(!q.empty())
    {
        TreeNode* cur = q.front();q.pop();
        int left = leftq.front();leftq.pop();
        int right = rightq.front();rightq.pop();
        int mid = left + (right - left) / 2;
        cur->val = nums[mid];
        if(left <= mid - 1)
        {
            cur->left = new TreeNode(0);
            q.push(cur->left);
            leftq.push(left);
            rightq.push(mid - 1);
        }
        if(right >= mid  + 1)
        {
            cur->right = new TreeNode(0);
            q.push(cur->right);
            leftq.push(mid + 1);
            rightq.push(right);
        }
    }
    return root;
}

int preVal = 0;

void transvel(TreeNode* root)
{
    if(nullptr == root)return;
    transvel(root->right);
    root->val += preVal;
    preVal = root->val;
    transvel(root->left);
}

void transvel_st(TreeNode* root)
{
    if(nullptr == root)return;
    stack<TreeNode*>st;
    TreeNode* cur = root;
    while(cur != nullptr || !st.empty())
    {
        if(cur != nullptr)
        {
            st.push(cur);
            cur = cur->right;
        }
        else
        {
            cur = st.top();st.pop();
            cur->val += preVal;
            preVal = cur->val;
            cur = cur->left;
        }
    }
}

TreeNode* convertBST(TreeNode* root)
{
    preVal = 0;
    // transvel(root);
    transvel_st(root);
    return root;
}


int main()
{
    //二叉树的三种遍历
    TreeNode t0(0);
    TreeNode t1(1);
    TreeNode t2(2);
    TreeNode t3(3);
    t0.left = &t1;
    t0.right = &t2;
    t2.right = &t3;
    vector<int>vec;
    print(visit(&t0));
    
    //二叉树的层序遍历
    print(levelOrder(&t0));

    //LeetCode107二叉树的层次遍历II
    print(levelOrderII(&t0));

    //LeetCode199二叉树的右视图
    print(rightSideView(&t0));

    //LeetCode637 二叉树的层平均值
    print<double>(averageofLevels(&t0));

    //LeetCode515 二叉树的层最大值
    print<int>(largestVals(&t0));

    //LeetCode116 填充每一个节点的下一个节点
    print(visit(connect(&t0)));

    //LeetCode117 填充每一个节点的下一个节点II
    //同LeetCode116

    //LeetCode226 翻转二叉树
    print(levelOrder(&t0));
    cout << "====" << endl;    
    print(levelOrder(invertTree(&t0)));
    print(levelOrder(dfs_invertTree(&t0)));
    cout << "====" << endl;    
    print(levelOrder(bfs_invertTree(&t0)));

    //LeetCode101对称二叉树
    TreeNode n0(1);
    TreeNode n1(2);
    TreeNode n2(2);
    TreeNode n3(3);
    TreeNode n4(4);
    TreeNode n5(3);
    TreeNode n6(4);
    n0.left = &n1;
    n0.right = &n2;
    n1.left = &n3;
    n1.right = &n4;
    n2.left = &n6;
    n2.right = &n5;
    print(levelOrder(&n0));
    cout << isSymmetric(&n0) << endl;
    cout << isSymmetric_queue(&n0) << endl;
    cout << isSymmetric_stack(&n0) << endl;

    //LeetCode104 二叉树的最大深度
    cout << getDepth(&n0) << endl;
    cout << getDepth_q(&n0) << endl;

    //LeetCode111 二叉树的最小深度
    cout << getMinDepth(&t0) << endl;
    cout << getMinDepth_q(&t0) << endl;

    //LeetCode222 二叉树的节点个数
    cout << getCountNums(&n0) << endl;
    cout << getCountNums_q(&n0) << endl;

    //LeetCode110 平衡二叉树
    cout << isBalance(&n0) <<endl;

    //LeetCode257 二叉树的所有路径    
    print<string>(binaryTreePath(&t0));
    print<string>(binaryTreePaths(&t0));

    //LeetCode404 左叶子之和
    cout << sumOfLeftLeaves(&t0) << endl;
    cout << sumOfLeftLeaves_st(&t0) << endl;
    
    
    //LeetCode513 树左下角的值    
    cout << findBottomLeftVal(&n0) << endl;

    //LeetCode112 路径总和
    print(levelOrder(&n0));
    cout << hasPathSum(&n0,1) << endl;
    cout << hasPathSum_st(&n0,7) << endl;

    //LeetCode113 路径总和II
    print(pathSum(&n0,6));

    //LeetCode106 从中序与后序遍历序列构造二叉树
    vector<int>inorder{9,3,15,20,7};
    vector<int>postorder{9,15,7,20,3};    
    print(levelOrder(buildTreeNode(inorder,postorder))); 

    //LeetCode105 从前序与中序遍历构造二叉树
    vector<int>preorder{3,9,20,15,7};
    print(levelOrder(buildTreeNodeII(preorder,inorder)));

    //LeetCode654 构造一棵最大的二叉树
    vector<int>nums{3,2,1,6,0,5};    
    print(levelOrder(constructMaxBinaryTree(nums)));

    //LeetCode617 合并二叉树
    TreeNode tr0(1);
    TreeNode tr1(3);
    TreeNode tr2(2);
    TreeNode tr3(5);
    TreeNode tl0(2);
    TreeNode tl1(1);
    TreeNode tl2(3);
    TreeNode tl3(4);
    TreeNode tl4(7);
    tr0.left = &tr1;
    tr0.right = &tr2;
    tr1.left = &tr3;

    tl0.left = &tl1;
    tl0.right = &tl2;
    tl1.right = &tl3;
    tl2.right = &tl4;
    print(levelOrder(&tr0));
    print(levelOrder(&tl0));
    // print(levelOrder(mergeTree(&tr0,&tl0)));
    // print(levelOrder(mergeTree_q(&tr0,&tl0)));

    //LeetCode700 二叉搜索树中的搜索
    print(levelOrder(searchBST(&tl0,3)));
    print(levelOrder(searchBST_iter(&tl0,3)));

    //LeetCode98 验证二叉搜索

标签:right,TreeNode,cur,nullptr,代码,随想录,二叉树,root,left
来源: https://www.cnblogs.com/fourmi/p/16284310.html