代码随想录第十八天 | 二叉树:找树左下角的值(递归/迭代:leetcode 513),路径总和(递归/迭代:leetcode 112,113),前中/中后序列构造二叉树(106,105)

1、找树左下角的值

1.1 leetcode 513:层序遍历(辅助队列)

第一遍代码:
辅助队列进行层序遍历

result作为二维vector不能直接插入int(想着可以通过插入vector<int>()来隔断,其实vector<int>()可以用来在二维数组中新建一行,详见下一节1.2:leetcode 513:层序遍历(递归))

class Solution {
public:
    //层序遍历最后一层的第一个元素
    vector<vector<int>> result;
    int order(TreeNode* cur) {
        queue<TreeNode*> myque;
        myque.push(cur);
        while(!myque.empty()) {
            int size = myque.size();
            vector<int> sline;
            for(int i = 0; i < size; i++) {
                TreeNode* tmp = myque.front();
                myque.pop();
                sline.push_back(tmp->val);
                if(tmp->left) myque.push(tmp->left);
                if(tmp->right) myque.push(tmp->right);
            }
            result.push_back(sline);
        }
        return result[result.size() - 1][0];
    }
    int findBottomLeftValue(TreeNode* root) {
        return order(root);
    }
};

迭代法
本题使用层序遍历再合适不过了

只需要记录最后一行第一个节点的数值就可以了,不需要像第一次代码中那样把整个遍历过程记录下来

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        int result = 0;
        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (i == 0) result = node->val; // 记录最后一行第一个元素
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return result;
    }
};

1.2 leetcode 513:先序遍历(递归)

递归进行先序遍历

class Solution {
public:
    //层序遍历最后一层的第一个元素
    vector<vector<int>> result;
    void order(TreeNode* cur, int depth) {
        if(cur == nullptr) return;
        if(depth == result.size()) result.push_back(vector<int>());
        result[depth].push_back(cur->val);
        order(cur->left, depth + 1);
        order(cur->right, depth + 1);
    }
    int findBottomLeftValue(TreeNode* root) {
        order(root, 0);
        return result[result.size() - 1][0];
    }
};

改进:不需要 记录下整个 递归序列,直接只记录 当前最深深度的最左节点

使用递归深度优先前序遍历求深度)遍历(非层序递归),其实就是找最大层的被遍历到的第一个元素

一直向左遍历到最后一个未必是最后一行

分析一下题目:在树的最后一行找到最左边的值
首先要是最后一行,然后是最左边的值

如果使用递归法,如何判断是最后一行呢,其实就是深度最大的叶子节点一定是最后一行
所以要找深度最大的叶子节点

那么如何找最左边的呢?可以使用前序遍历(当然中序,后序都可以,因为本题没有中间节点的处理逻辑,只要左优先就行),保证优先左边搜索,然后记录深度最大的叶子节点,此时就是树的最后一行最左边的值

递归三部曲:
1、确定递归函数的参数和返回值
参数必须有要遍历的树的根节点,还有就是一个int型的变量用来记录最大深度。 这里就不需要返回值了,所以递归函数的返回类型为void

本题还需要类里的两个全局变量,maxLen用来记录最大深度,result记录最大深度最左节点的数值不需要像第一遍代码那样记录下完整遍历序列

代码如下:

int maxDepth = INT_MIN;   // 全局变量 记录最大深度
int result;       // 全局变量 最大深度最左节点的数值
void traversal(TreeNode* root, int depth)

2、确定终止条件
遇到叶子节点的时候,就需要统计一下最大的深度了,所以需要遇到叶子节点来更新最大深度

代码如下:

if (root->left == NULL && root->right == NULL) {
    if (depth > maxDepth) {
        maxDepth = depth;           // 更新最大深度
        result = root->val;   // 最大深度最左面的数值
    }
    return;
}

3、确定单层递归的逻辑
在找最大深度的时候,递归的过程中依然要使用回溯
代码如下:


                   // 中(没有中间节点的逻辑,纯遍历)
if (root->left) {   // 左
    depth++; // 深度加一
    traversal(root->left, depth);
    depth--; // 回溯,深度减一
}
if (root->right) { // 右
    depth++; // 深度加一
    traversal(root->right, depth);
    depth--; // 回溯,深度减一
}
return;

看完思路写代码:

因为递归退出逻辑里面没有判断节点是否为空的部分,所以在加入递归(使用递归函数)前要判断一下,不能为空节点

depth+1包含着回溯

class Solution {
public:
    //层序遍历最后一层的第一个元素
    int result;
    int maxDepth = -1;
    void order(TreeNode* cur, int depth) {
        //因为递归退出逻辑里面没有判断节点是否为空的部分,所以在加入递归(使用递归函数)前要判断一下,不能为空节点
        if(cur->left == nullptr && cur->right == nullptr) {
            if(depth > maxDepth) {
                maxDepth = depth;
                result = cur->val;
            }
            return;
        }
        if(cur->left) order(cur->left, depth + 1);//depth+1包含着回溯
        if(cur->right) order(cur->right, depth + 1);
    }
    int findBottomLeftValue(TreeNode* root) {
        order(root, 0);
        return result;
    }
};

1.3 leetcode 513:后序迭代遍历 求最大实时深度

1.2节 思路实现一致,只是多了一个在 第一次遍历到这个深度的元素时 做记录,因为每层 第一个被遍历到的 一定是最左边的(后序遍历 中左右 还是左先遍历到

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        stack<TreeNode*> sta;
        int depth = 0;
        int res;
        int maxDep = 0;
        if (root) sta.push(root);
        while (!sta.empty()) {
            TreeNode* tmp = sta.top();
            sta.pop();
            if (tmp != nullptr) {
                depth++;
                if (depth > maxDep) {
                    maxDep = depth;
                    res = tmp->val;
                }
                sta.push(tmp);
                sta.push(nullptr);
                if (tmp->right) sta.push(tmp->right); // 后序同样是先左再右(入栈 先右后左)
                if (tmp->left) sta.push(tmp->left);
            }
            else {
                sta.pop();
                depth--;
            }
        }
        return res;
    }
};

1.4 leetcode 513:总结

本题涉及如下几点:
1、递归求深度的写法,我们在leetcode 110中详细的分析了深度应该怎么求,高度应该怎么求,以及什么时候 最大高度 就是 最大深度(1.3节)

2、递归中其实隐藏了回溯,在leetcode 257中讲解了究竟哪里使用了回溯,哪里隐藏了回溯

3、层次遍历,在代码随想录第十五天讲解了二叉树层次遍历

2、路径总和

2.1 leetcode 112:深度优先(递归先序遍历)

第一次代码
递归先序遍历参数带路径之和

class Solution {
public:
    //递归先序遍历,参数带路径之和
    bool order(TreeNode* cur, int curSum, int targetSum) {
        if(cur->left == nullptr && cur->right == nullptr) {
            if(curSum == targetSum) {
                return true;
            }
            else {
                return false;
            }
        }
        bool leftjudge;
        bool rightjudge;
        if(cur->left) leftjudge = order(cur->left, curSum + cur->left->val, targetSum);
        if(cur->right) rightjudge = order(cur->right, curSum + cur->right->val, targetSum);
        return leftjudge || rightjudge;
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr) return false;
        return order(root, root->val, targetSum);
    }
};

递归
可以使用深度优先遍历的方式(本题前中后序都可以,无所谓,因为中节点也没有处理逻辑)来遍历二叉树

1、确定递归函数的参数和返回类型
参数:需要二叉树的根节点,还需要一个计数器,这个计数器用来计算二叉树的一条边之和是否正好是目标和,计数器为int型

再来看返回值,递归函数什么时候需要返回值?什么时候不需要返回值?这里总结如下三点:

1、如果需要搜索整棵二叉树不用处理递归返回值,递归函数就不要返回值(leetcode 113)
2、如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值(leetcode 236)
3、如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回判断(本题的情况)

总而言之,要看需不需要处理递归返回值,或者是否需要及时知道递归的结果,需要用到多次递归的结果的,还可以考虑使用全局参数

而本题我们要找一条符合条件的路径,所以递归函数需要返回值,及时返回
leetcode 112:深度优先
图中可以看出遍历的路线,并不要遍历整棵树,所以递归函数需要返回值,可以用bool类型表示
所以代码如下:

bool traversal(treenode* cur, int count)   // 注意函数的返回类型

2、确定终止条件
首先计数器如何统计这一条路径的和呢?
不要累加然后判断是否等于目标和,那么可以少传一个 参数第一次代码的实现方法)

可以用递减,让计数器count初始为目标和,然后每次减去遍历路径节点上的数值,之后直接与0比较就行了

如果最后count == 0,同时到了叶子节点的话,说明找到了目标和
如果遍历到了叶子节点count不为0,就是没找到

递归终止条件代码如下:

if (!cur->left && !cur->right && count == 0) return true; // 遇到叶子节点,并且计数为0
if (!cur->left && !cur->right) return false; // 遇到叶子节点而没有找到合适的边,直接返回

3、确定单层递归的逻辑
因为终止条件是判断叶子节点,所以递归的过程中就不要让空节点进入递归了
递归函数是有返回值的,如果递归函数返回true,说明找到了合适的路径,需要及时处理,应该立刻返回

代码如下:

if (cur->left) { // 左 (空节点不遍历)
    // 遇到叶子节点返回true,则直接返回true
    if (traversal(cur->left, count - cur->left->val)) return true; // 注意这里有回溯的逻辑
}
if (cur->right) { // 右 (空节点不遍历)
    // 遇到叶子节点返回true,则直接返回true
    if (traversal(cur->right, count - cur->right->val)) return true; // 注意这里有回溯的逻辑
}
return false;

以上代码中是包含着回溯的,回溯隐藏在traversal(cur->left, count - cur->left->val)这里, 因为把count - cur->left->val直接作为参数传进去,函数结束,count的数值没有改变

整体代码

class Solution {
private:
    bool traversal(TreeNode* cur, int count) {
        if (!cur->left && !cur->right && count == 0) return true; // 遇到叶子节点,并且计数为0
        if (!cur->left && !cur->right) return false; // 遇到叶子节点直接返回

        if (cur->left) { // 左
            count -= cur->left->val; // 递归,处理节点;
            if (traversal(cur->left, count)) return true;
            count += cur->left->val; // 回溯,撤销处理结果
        }
        if (cur->right) { // 右
            count -= cur->right->val; // 递归,处理节点;
            if (traversal(cur->right, count)) return true;
            count += cur->right->val; // 回溯,撤销处理结果
        }
        return false;
    }
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if (root == NULL) return false;
        return traversal(root, sum - root->val);
    }
};

简化代码:

class Solution {
public:
    bool isTargetSum(TreeNode* cur, int count) {
        count -= cur->val;
        if (cur->left == nullptr && cur->right == nullptr)
            if (count == 0) return true;
            else return false;
        if (cur->left)
            if (isTargetSum(cur->left, count))
                return true;
        if (cur->right)
            if (isTargetSum(cur->right, count))
                return true;
        return false;
    }

    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == nullptr) return false;
        return isTargetSum(root, targetSum);
    }
};

2.2 leetcode 112:统一迭代法后序遍历

如果使用栈模拟递归的话,那么如果做回溯呢?

此时栈里一个元素不仅要记录该节点指针还要记录从头结点到该节点的路径数值总和
c++就我们用pair结构来存放这个栈里的元素
定义为:pair<TreeNode*, int> pair<节点指针,路径数值>
这个为栈里的一个元素

使用栈模拟的前序遍历,看完思路写代码:

后序遍历在弹出指针不为空时先push中间节点(统一迭代真正空节点前中后序入栈顺序,完全按照前中后序的顺序的倒序

别忘了压入中间节点,注意nullptr只能赋给pair第一个元素,因为只有指针才可以塞空指针

注意,在后面的代码中,之前if前pop过了,这里不需要再pop

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        //统一迭代法使用后序遍历
        if(root == nullptr) return false;
        stack<pair<TreeNode*, int>> mystack;
        mystack.push(pair<TreeNode*, int>(root, root->val));
        while(!mystack.empty()) {
            pair<TreeNode*, int> tmp = mystack.top();
            mystack.pop();
            if(tmp.first != nullptr) {
                mystack.push(tmp);//后序遍历先push中间节点(统一迭代完全按照顺序)
                mystack.push(pair<TreeNode*, int>(nullptr, 0));//别忘了压入中间节点,注意nullptr只能赋给pair第一个元素,因为只有指针才可以塞空指针
                if(tmp.first->right) {
                    mystack.push(pair<TreeNode*, int>(tmp.first->right, tmp.second + tmp.first->right->val));
                }
                if(tmp.first->left) {
                    mystack.push(pair<TreeNode*, int>(tmp.first->left, tmp.second + tmp.first->left->val));
                }
               
            }
            else {
                //之前if前pop过了,这里不需要再pop了
                pair<TreeNode*, int> tmp2 = mystack.top();
                mystack.pop();
                if(tmp2.first->left == nullptr && tmp2.first->right == nullptr) {
                    if(tmp2.second == targetSum) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
};

统一迭代法 后序遍历另一种实现
完美体现了 统一迭代法后序遍历(只有后序遍历。前序中序 不一样)的两次弹出过程
第一次弹出 都是一条道走到头,第二次弹出 再换路径(回溯过程)

class Solution {
public:
    bool getSum(TreeNode* root, int count) {
        stack<TreeNode*> sta;
        if (root) sta.push(root);
        while (!sta.empty()) {
            TreeNode* cur = sta.top();
            sta.pop();
            if (cur != nullptr) { // 第一次弹出 都是一条道走到头,第二次弹出 再换路径(回溯过程)
                count -= cur->val;
                sta.push(cur);
                sta.push(nullptr);
                if (cur->left == nullptr && cur->right == nullptr) {
                    if (count == 0)
                        return true;
                }
                if (cur->right) sta.push(cur->right);
                if (cur->left) sta.push(cur->left);
            }
            else {
                cur = sta.top();
                sta.pop();
                count += cur->val;
            }
        }
        return false;
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == nullptr) return false;
        return getSum(root, targetSum);
    }
};

2.3 leetcode 112:统一迭代法前序遍历

与后序的区别仅仅是

mystack.push(tmp);//前序遍历最后push中间节点(统一迭代完全按照顺序)
mystack.push(pair<TreeNode*, int>(nullptr, 0));

这两行的相对于左右节点的入栈位置
第一遍完整代码:

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        //统一迭代法使用前序遍历
        if(root == nullptr) return false;
        stack<pair<TreeNode*, int>> mystack;
        mystack.push(pair<TreeNode*, int>(root, root->val));
        while(!mystack.empty()) {
            pair<TreeNode*, int> tmp = mystack.top();
            mystack.pop();
            if(tmp.first != nullptr) {
                if(tmp.first->right) {
                    mystack.push(pair<TreeNode*, int>(tmp.first->right, tmp.second + tmp.first->right->val));
                }
                if(tmp.first->left) {
                    mystack.push(pair<TreeNode*, int>(tmp.first->left, tmp.second + tmp.first->left->val));
                }
                mystack.push(tmp);//前序遍历最后push中间节点(统一迭代完全按照顺序)
                mystack.push(pair<TreeNode*, int>(nullptr, 0));
               
            }
            else {
                //之前if前pop过了,这里不需要再pop了
                pair<TreeNode*, int> tmp2 = mystack.top();
                mystack.pop();
                if(tmp2.first->left == nullptr && tmp2.first->right == nullptr) {
                    if(tmp2.second == targetSum) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
};

2.4 leetcode 112:非统一迭代前序遍历

代码随想录使用非统一迭代前序遍历的代码

class solution {

public:
    bool haspathsum(TreeNode* root, int sum) {
        if (root == null) return false;
        // 此时栈里要放的是pair<节点指针,路径数值>
        stack<pair<TreeNode*, int>> st;
        st.push(pair<TreeNode*, int>(root, root->val));
        while (!st.empty()) {
            pair<TreeNode*, int> node = st.top();
            st.pop();
            // 如果该节点是叶子节点了,同时该节点的路径数值等于sum,那么就返回true
            if (!node.first->left && !node.first->right && sum == node.second) return true;

            // 右节点,压进去一个节点的时候,将该节点的路径数值也记录下来
            if (node.first->right) {
                st.push(pair<TreeNode*, int>(node.first->right, node.second + node.first->right->val));
            }

            // 左节点,压进去一个节点的时候,将该节点的路径数值也记录下来
            if (node.first->left) {
                st.push(pair<TreeNode*, int>(node.first->left, node.second + node.first->left->val));
            }
        }
        return false;
    }
};

2.5 leetcode 113:深度优先(递归)

与leetcode 112相比,不仅要判断是否,还要返回所有满足条件的路径,使用全局参数+函数参数使用记录路径的vector参数解决

class Solution {
public:
//与leetcode 112相比,不仅要判断是否,还要返回所有满足条件的路径,使用全局参数+记录路径的vector参数解决
    vector<vector<int>> result;
    void order(TreeNode* cur, vector<int>& record, int curSum, int targetSum) {
        if(cur->left == nullptr && cur->right == nullptr) {
            if(curSum == targetSum) {
                result.push_back(record);
            }
            return;
        }
        if(cur->left) {
            record.push_back(cur->left->val);
            order(cur->left, record, curSum + cur->left->val, targetSum);
            record.pop_back();
        }
        if(cur->right) {
            record.push_back(cur->right->val);
            order(cur->right, record, curSum + cur->right->val, targetSum);
            record.pop_back();
        }
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        if(root == nullptr) return result;
        vector<int> re;
        re.push_back(root->val);
        order(root, re, root->val, targetSum);
        return result;
    }
};

路径总和ii要遍历整个树找到所有路径,所以递归函数不要返回值

代码随想录递归代码,使用count记录距离目标节点和还差多少,这样相比较于第一次代码的递归函数的参数可以减少一个

class solution {
private:
    vector<vector<int>> result;
    vector<int> path;
    // 递归函数不需要返回值,因为我们要遍历整个树
    void traversal(TreeNode* cur, int count) {
        if (!cur->left && !cur->right && count == 0) { // 遇到了叶子节点且找到了和为sum的路径
            result.push_back(path);
            return;
        }
        if (!cur->left && !cur->right) return ; // 遇到叶子节点而没有找到合适的边,直接返回

        if (cur->left) { // 左 (空节点不遍历)
            path.push_back(cur->left->val);
            count -= cur->left->val;
            traversal(cur->left, count);    // 递归
            count += cur->left->val;        // 回溯
            path.pop_back();                // 回溯
        }
        if (cur->right) { // 右 (空节点不遍历)
            path.push_back(cur->right->val);
            count -= cur->right->val;
            traversal(cur->right, count);   // 递归
            count += cur->right->val;       // 回溯
            path.pop_back();                // 回溯
        }
        return ;
    }

public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        result.clear();
        path.clear();
        if (root == NULL) return result;
        path.push_back(root->val); // 把根节点放进路径
        traversal(root, sum - root->val);
        return result;
    }
};

跟上一节一样,一样可以用统一迭代法 后序遍历另一种实现实现
其中的两次弹出过程
第一次弹出 都是一条道走到头,第二次弹出 再换路径(回溯过程)

class Solution {
public:
    vector<vector<int>> res;
    void getPath(TreeNode* root, int count) {
        stack<TreeNode*> sta;
        if (root) sta.push(root);
        vector<int> curPath;
        while (!sta.empty()) {
            TreeNode* tmp = sta.top();
            sta.pop();
            if (tmp != nullptr) {
                curPath.push_back(tmp->val);
                count -= tmp->val;
                if (tmp->left == nullptr && tmp->right == nullptr && count == 0) {
                    res.push_back(curPath);
                }
                sta.push(tmp);
                sta.push(nullptr);
                if (tmp->right) sta.push(tmp->right);
                if (tmp->left) sta.push(tmp->left);
            }
            else {
                tmp = sta.top();
                sta.pop();
                curPath.pop_back();
                count += tmp->val;
            }
        }
    }

    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        getPath(root, targetSum);
        return res;
    }
};

2.6 路径总和总结

通过 leetcode 112 和 leetcode 113 详细的讲解了递归函数什么时候需要返回值,什么不需要返回值,感受到搜索整棵树 和 搜索某一路径的差别

3、前中序/中后序构造二叉树

3.1 leetcode 106:中后序构造二叉树

其实对于每一棵树,包括其子树和以其为左/右子树的树,所有的树的构建都是基于长度相同的中序遍历序列和后序遍历序列

基于此,采用递归的方法(每一小步相同),每一次递归函数搞好一个节点及将其指向左右子树左右子树下一层递归搞定(自然需要划分新的属于左/子树的后序和中序序列),最后终止条件就是子树为空(自然确定一棵树的中序序列/后序序列中不包含元素了)

所以问题变成怎么划分出对应节点的左右子树对应的中序和后序序列

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.size() == 0) return nullptr;
        TreeNode* cur = new TreeNode(postorder.back());
        vector<int> left_postorder;
        vector<int> left_inorder;
        int i = 0;
        for (; inorder[i] != postorder.back(); i++) {
            left_inorder.push_back(inorder[i]);
            left_postorder.push_back(postorder[i]);
        }
        cur->left = buildTree(left_inorder, left_postorder);
        vector<int> right_postorder;
        vector<int> right_inorder;
        for (int j = i + 1; j < inorder.size(); j++) {
            right_inorder.push_back(inorder[j]);
            right_postorder.push_back(postorder[j - 1]); // 注意这里不是postorder[j]了,下标不同了
        }
        cur->right = buildTree(right_inorder, right_postorder);
        return cur;
    }
};

根据两个顺序构造一个唯一的二叉树:以后序数组的最后一个元素为切割点先切中序数组,根据中序数组,反过来再切后序数组一层一层切下去,每次 后序数组最后一个元素(也就是根,不是第一个元素)就是当前节点(子树的 根)元素
构造二叉树的过程
那么代码应该怎么写呢?

说到一层一层切割,且每一小步都相同层层嵌套,就应该想到了递归

一共分六步:
第一步:如果数组大小为零的话,说明是空节点了
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
第四步:切割中序数组,切成中序左数组中序右数组 (顺序别搞反了,一定是先切中序数组,这样才知道左右子树的 大小和元素)
第五步:切割后序数组,切成后序左数组后序右数组
第六步:递归处理左区间和右区间

先把框架写出来

TreeNode* traversal (vector<int>& inorder, vector<int>& postorder) {

    // 第一步
    if (postorder.size() == 0) return NULL;

    // 第二步:后序遍历数组最后一个元素,就是当前的中间节点
    int rootValue = postorder[postorder.size() - 1];
    TreeNode* root = new TreeNode(rootValue);

    // 叶子节点
    if (postorder.size() == 1) return root;

    // 第三步:找切割点
    int delimiterIndex;
    for (delimiterIndex = 0; delimiterIndex < inorder.size(); delimiterIndex++) {
        if (inorder[delimiterIndex] == rootValue) break;
    }

    // 第四步:切割中序数组,得到 中序左数组和中序右数组
    // 第五步:切割后序数组,得到 后序左数组和后序右数组

    // 第六步
    root->left = traversal(中序左数组, 后序左数组);
    root->right = traversal(中序右数组, 后序右数组);

    return root;
}

难点就是如何切割,以及边界值找不好很容易乱套

此时应该注意确定切割的标准,是左闭右开,还有左开右闭,还是左闭右闭,这个就是不变量,要在递归中保持这个不变量(第一遍代码中为左闭右闭)
在切割的过程中会产生四个区间,把握不好不变量的话,一会左闭右开,一会左闭右闭,必然乱套
循环不变量的重要性,在二分查找以及螺旋矩阵的求解中,坚持循环不变量非常重要,本题也是

首先要切割中序数组,为什么先切割中序数组呢?
切割点在后序数组的最后一个元素,就是用这个元素来切割中序数组的,所以必要先切割中序数组

中序数组相对比较好切,找到切割点(后序数组的最后一个元素,即中间节点)在中序数组的位置,然后切割,如下代码中代码随想录坚持左闭右开的原则:

// 找到中序遍历的切割点
int delimiterIndex;
for (delimiterIndex = 0; delimiterIndex < inorder.size(); delimiterIndex++) {
    if (inorder[delimiterIndex] == rootValue) break;
}

// 左闭右开区间:[0, delimiterIndex)
vector<int> leftInorder(inorder.begin(), inorder.begin() + delimiterIndex);
// [delimiterIndex + 1, end)
vector<int> rightInorder(inorder.begin() + delimiterIndex + 1, inorder.end() );

接下来就要切割后序数组
首先后序数组的最后一个元素指定不能要了,这是切割点也是当前二叉树中间节点的元素,已经用了

后序数组切割点怎么找?
后序数组没有明确的切割元素来进行左右切割,是通过中序数组大小一定是和后序数组的大小相同的(即元素个数)来切割的
中序数组我们都切成了左中序数组和右中序数组了,那么后序数组就可以按照左中序数组的大小来切割,切成左后序数组和右后序数组

代码如下:

// postorder 舍弃末尾元素,因为这个元素就是中间节点,已经用过了
postorder.resize(postorder.size() - 1);

// 左闭右开,注意这里使用了左中序数组大小作为切割点:[0, leftInorder.size)
vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
// [leftInorder.size(), end)
vector<int> rightPostorder(postorder.begin() + leftInorder.size(), postorder.end());

完整代码如下:

class Solution {
private:
    TreeNode* traversal (vector<int>& inorder, vector<int>& postorder) {
        if (postorder.size() == 0) return NULL;

        // 后序遍历数组最后一个元素,就是当前的中间节点
        int rootValue = postorder[postorder.size() - 1];
        TreeNode* root = new TreeNode(rootValue);

        // 叶子节点
        if (postorder.size() == 1) return root;

        // 找到中序遍历的切割点
        int delimiterIndex;
        for (delimiterIndex = 0; delimiterIndex < inorder.size(); delimiterIndex++) {
            if (inorder[delimiterIndex] == rootValue) break;
        }

        // 切割中序数组
        // 左闭右开区间:[0, delimiterIndex)
        vector<int> leftInorder(inorder.begin(), inorder.begin() + delimiterIndex);
        // [delimiterIndex + 1, end)
        vector<int> rightInorder(inorder.begin() + delimiterIndex + 1, inorder.end() );

        // postorder 舍弃末尾元素
        postorder.resize(postorder.size() - 1);

        // 切割后序数组
        // 依然左闭右开,注意这里使用了左中序数组大小作为切割点
        // [0, leftInorder.size)
        vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
        // [leftInorder.size(), end)
        vector<int> rightPostorder(postorder.begin() + leftInorder.size(), postorder.end());

        root->left = traversal(leftInorder, leftPostorder);
        root->right = traversal(rightInorder, rightPostorder);

        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.size() == 0 || postorder.size() == 0) return NULL;
        return traversal(inorder, postorder);
    }
};

3.2 leetcode 106:中后序构造二叉树改进(使用数组下标)

如上的代码性能并不好,因为每层递归定义了新的vector(就是数组),既耗时又耗空间,但上面的代码是最好理解的

下面给出用下标索引写出的代码版本:(思路是一样的,只不过不用重复定义vector了,每次用下标索引来分割,注意传入的下标参数,不区分左右(还没划分))

class Solution {
private:
    // 中序区间:[inorderBegin, inorderEnd),后序区间[postorderBegin, postorderEnd)
    TreeNode* traversal (vector<int>& inorder, int inorderBegin, int inorderEnd, vector<int>& postorder, int postorderBegin, int postorderEnd) {
        if (postorderBegin == postorderEnd) return NULL;

        int rootValue = postorder[postorderEnd - 1];
        TreeNode* root = new TreeNode(rootValue);

        if (postorderEnd - postorderBegin == 1) return root;

        int delimiterIndex;
        for (delimiterIndex = inorderBegin; delimiterIndex < inorderEnd; delimiterIndex++) {
            if (inorder[delimiterIndex] == rootValue) break;
        }
        // 切割中序数组
        // 左中序区间,左闭右开[leftInorderBegin, leftInorderEnd)
        int leftInorderBegin = inorderBegin;
        int leftInorderEnd = delimiterIndex;
        // 右中序区间,左闭右开[rightInorderBegin, rightInorderEnd)
        int rightInorderBegin = delimiterIndex + 1;
        int rightInorderEnd = inorderEnd;

        // 切割后序数组
        // 左后序区间,左闭右开[leftPostorderBegin, leftPostorderEnd)
        int leftPostorderBegin =  postorderBegin;
        int leftPostorderEnd = postorderBegin + delimiterIndex - inorderBegin; // 终止位置是 需要加上 中序区间的大小size
        // 右后序区间,左闭右开[rightPostorderBegin, rightPostorderEnd)
        int rightPostorderBegin = postorderBegin + (delimiterIndex - inorderBegin);
        int rightPostorderEnd = postorderEnd - 1; // 排除最后一个元素,已经作为节点了

        root->left = traversal(inorder, leftInorderBegin, leftInorderEnd,  postorder, leftPostorderBegin, leftPostorderEnd);
        root->right = traversal(inorder, rightInorderBegin, rightInorderEnd, postorder, rightPostorderBegin, rightPostorderEnd);

        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.size() == 0 || postorder.size() == 0) return NULL;
        // 左闭右开的原则
        return traversal(inorder, 0, inorder.size(), postorder, 0, postorder.size());
    }
};

3.3 leetcode 105:前中序构造二叉树(对数组下标操作)

第一遍代码,采用leetcode 106中的对数组下标的操作方法,并采用前闭后闭的原则

class Solution {
public:
//通过使用下标的方法避免反复创造vector数组,前闭后闭
    TreeNode* build(vector<int> preorder, int pre_b, int pre_e, vector<int> inorder, int in_b, int in_e) {
        if(pre_b > pre_e) {//注意是前闭后闭
            return nullptr;
        }
        int div = preorder[pre_b];
        TreeNode* cur = new TreeNode(preorder[pre_b]);
        int left_pre_b = ++pre_b;
        int left_pre_e;
        int left_in_b = in_b;
        int left_in_e;
        int right_pre_b;
        int right_pre_e = pre_e;
        int right_in_b;
        int right_in_e = in_e;
        for(int i = in_b; i <= in_e; i++) {
            if(inorder[i] == div) {
                left_in_e = i - 1;
                right_in_b = i + 1;
                break;
            }
        }
        left_pre_e = pre_b + left_in_e - left_in_b;
        right_pre_b = right_pre_e - (right_in_e - right_in_b);
        cur->left = build(preorder, left_pre_b, left_pre_e, inorder, left_in_b, left_in_e);
        cur->right = build(preorder, right_pre_b, right_pre_e, inorder, right_in_b, right_in_e);
        return cur;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
    }
};

代码随想录代码,同样是对下标操作整递归,但是采用左开右闭

class Solution {
private:
        TreeNode* traversal (vector<int>& inorder, int inorderBegin, int inorderEnd, vector<int>& preorder, int preorderBegin, int preorderEnd) {
        if (preorderBegin == preorderEnd) return NULL;

        int rootValue = preorder[preorderBegin]; // 注意用preorderBegin 不要用0
        TreeNode* root = new TreeNode(rootValue);

        if (preorderEnd - preorderBegin == 1) return root;

        int delimiterIndex;
        for (delimiterIndex = inorderBegin; delimiterIndex < inorderEnd; delimiterIndex++) {
            if (inorder[delimiterIndex] == rootValue) break;
        }
        // 切割中序数组
        // 中序左区间,左闭右开[leftInorderBegin, leftInorderEnd)
        int leftInorderBegin = inorderBegin;
        int leftInorderEnd = delimiterIndex;
        // 中序右区间,左闭右开[rightInorderBegin, rightInorderEnd)
        int rightInorderBegin = delimiterIndex + 1;
        int rightInorderEnd = inorderEnd;

        // 切割前序数组
        // 前序左区间,左闭右开[leftPreorderBegin, leftPreorderEnd)
        int leftPreorderBegin =  preorderBegin + 1;
        int leftPreorderEnd = preorderBegin + 1 + delimiterIndex - inorderBegin; // 终止位置是起始位置加上中序左区间的大小size
        // 前序右区间, 左闭右开[rightPreorderBegin, rightPreorderEnd)
        int rightPreorderBegin = preorderBegin + 1 + (delimiterIndex - inorderBegin);
        int rightPreorderEnd = preorderEnd;

        root->left = traversal(inorder, leftInorderBegin, leftInorderEnd,  preorder, leftPreorderBegin, leftPreorderEnd);
        root->right = traversal(inorder, rightInorderBegin, rightInorderEnd, preorder, rightPreorderBegin, rightPreorderEnd);

        return root;
    }

public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if (inorder.size() == 0 || preorder.size() == 0) return NULL;

        // 参数坚持左闭右开的原则
        return traversal(inorder, 0, inorder.size(), preorder, 0, preorder.size());
    }
};

自己实现,注意注释

class Solution {
public:
    TreeNode* buildT(const vector<int> preorder, int preBegin, int preEnd, const vector<int> inorder, int inBegin, int inEnd) {
        if (preEnd - preBegin == 0) return nullptr;
        TreeNode *cur = new TreeNode(preorder[preBegin]);
        int diviPoint = inBegin;
        for (; inorder[diviPoint] != preorder[preBegin]; diviPoint++);
        cur->left = buildT(preorder, preBegin + 1, preBegin + diviPoint - inBegin + 1, inorder, inBegin, diviPoint); // preBegin + diviPoint - inBegin + 1 后面是+1不是+2,左闭右开,diviPoint - inBegin直接是大小,直接加上preBegin + 1就行了,自然多出来1个
        cur->right = buildT(preorder, preBegin + diviPoint - inBegin + 1, preEnd, inorder, diviPoint + 1, inEnd);
        return cur;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildT(preorder, 0, preorder.size(), inorder, 0, inorder.size());
    }
};

3.4 两种序列构造二叉树拓展

前序和中序可以唯一确定一棵二叉树
后序和中序可以唯一确定一棵二叉树

那么前序和后序可不可以唯一确定一棵二叉树呢?
前序和后序不能唯一确定一棵二叉树!因为没有中序遍历无法确定左右部分,也就是无法分割(必须包含一个中序遍历),前序后序的作用 都是提取出 子树的根节点
前后序无法构造二叉树
tree1 的前序遍历是[1 2 3], 后序遍历是[3 2 1]
tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]

那么tree1 和 tree2 的前序和后序完全相同,这是一棵树么,很明显是两棵树
所以前序和后序不能唯一确定一棵二叉树

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值