带你手撕单调栈(二)

带你手撕单调栈(二)

思路请看

描述

给定一个整形数组arr,已知其中所有的值都是非负的,将这个数组看作一个柱子高度图,计算按此排列的柱子,下雨之后能接多少雨水。

img

示例1

输入:

[3,1,2,5,2,4]  

复制

返回值:

5 

复制

说明:

数组 [3,1,2,5,2,4] 表示柱子高度图,在这种情况下,可以接 5个单位的雨水,蓝色的为雨水 

示例2

输入:

[4,5,1,3,2]

返回值:

2 
class Solution {
public:
    /**
     * max water
     * @param arr int整型vector the array
     * @return long长整型
     */
    long long maxWater(vector<int>& arr) {
        // write code here
        /**
            拿到题目先分析
            这个东西,要知道某个地点能蓄水多少就要知道左边比自己高的第一个高度是多少,右边的比自己高的第一个高度是多少
            那么怎么求右边比自己高度是多少
            又发现是一个先进后出的结构,正好要计算左右,那么我们就一正一反的来
        **/
        // 先求右边,这是正向的,处理在while里面
        stack<int> st;
        vector<int> right_high(arr.size(),-1);
        for(int i=0;i<arr.size();i++) {
            while(!st.empty() && arr[st.top()]<=arr[i]) {
                right_high[st.top()] = i;
                st.pop();  // 正的不能直接pop后不管
            }
            
            st.push(i);
        }
        
        // 清空st
        while(!st.empty()) {
            st.pop();
        }
        
        // 开始倒序,加入哨兵节点
        arr.insert(arr.begin(), 0);
        vector<int> left_hight(arr.size());
        for(int i=0;i<arr.size();i++) {
            while(!st.empty() && arr[st.top()]<=arr[i]) {
                st.pop();
            }
            left_hight[i]=st.empty()?-1:st.top()-1; // 这是反向的处理在while外面
            st.push(i);
        }
        left_hight.erase(left_hight.begin());
        arr.erase(arr.begin());
        
//         for(auto value : left_hight) {
//             cout<<value<<" ";
//         }
//         cout<<endl;
//         for(auto value : right_high) {
//             cout<<value<<" ";
//         }
//         cout<<endl;
        
        long long res = 0;
        for(int i=0;i<left_hight.size();i++) {
            if(left_hight[i]>=0 && right_high[i]>=0) {
                res+=(min(arr[left_hight[i]],arr[right_high[i]])-arr[i])*(long long)(right_high[i]-left_hight[i]-1);
            }
        }
        return res;
        
    }
};
<think>我们被要求使用Python实现叉树的中序遍历,并提供相关练习题。 中序遍历的顺序是:左子树 -> 根节点 -> 右子树。 根据引用,我们可以总结几种常见的实现方法: 1. 递归法(直接递归) 2. 迭代法(使用栈模拟递归过程) 3. Morris遍历(最优算法,但相对复杂,这里暂不展示,因为引用中未提及) 另外,引用[4]提到Python存在递归深度限制,所以递归方法可能需要调整递归深度。 下面我们将展开代码实现,并尽可能提供多种方法。 首先,定义叉树的节点类(通常题目中已经给出,但为了完整,我们在这里定义): class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right 方法一:递归法(标准求解) - 递归终止条件:节点为空 - 先递归遍历左子树,然后访问根节点,再递归遍历右子树。 方法:迭代法(使用栈) - 使用一个栈来模拟递归过程。 - 从根节点开始,将所有左子节点依次入栈,直到左子节点为空。 - 弹出栈顶元素,访问该节点,然后转向该节点的右子树。 - 重复上述过程直到栈为空且当前节点为空。 方法三:函数递归的改进(这里其实是另一种递归写法,但引用中并未明显区分,我们可参考其他写法) 根据引用[2],我们可以写出迭代法的代码,但需要注意的是,引用[2]给出的是前序遍历的迭代写法,中序遍历的迭代写法略有不同。 我们参考常见的迭代写法来实现中序遍历。 下面我们给出代码: 注意:我们在代码中会包含必要的注释,以便理解。 </think>### Python实现叉树中序遍历的代码 叉树的中序遍历顺序为:**左子树 &rarr; 根节点 &rarr; 右子树**。以下是三种实现方法: #### 1. 递归法(标准求解) ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorderTraversal(root: TreeNode) -> list: res = [] def _inorder(node): if not node: return _inorder(node.left) # 递归左子树 res.append(node.val) # 访问根节点 _inorder(node.right) # 递归右子树 _inorder(root) return res ``` **特点**:代码简洁,时间复杂度 $O(n)$,空间复杂度 $O(h)$($h$ 为树高)[^1][^4]。 #### 2. 迭代法(栈模拟) ```python def inorderTraversal(root: TreeNode) -> list: res, stack = [], [] cur = root while cur or stack: # 将左子节点全部入栈 while cur: stack.append(cur) cur = cur.left # 访问栈顶节点(最深层左子节点) node = stack.pop() res.append(node.val) # 转向右子树 cur = node.right return res ``` **特点**:显式栈替代递归栈,避免递归深度限制问题[^2]。 #### 3. 迭代法(通用模板) ```python def inorderTraversal(root: TreeNode) -> list: res, stack = [], [] if root: stack.append(root) while stack: node = stack.pop() if node: # 右子节点入栈 if node.right: stack.append(node.right) # 当前节点次入栈(标记未访问) stack.append(node) stack.append(None) # 添加空节点作为访问标记 # 左子节点入栈 if node.left: stack.append(node.left) else: # 遇到空标记时,访问下一节点 node = stack.pop() res.append(node.val) return res ``` **特点**:统一的前中后序遍历模板,通过 `None` 标记已处理节点[^2]。 --- ### 相关练习题(附LeetCode链接) 1. **基础应用** [94. 叉树的中序遍历](https://leetcode.com/problems/binary-tree-inorder-traversal/) [530. 叉搜索树的最小绝对差](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)(利用中序遍历有序性) 2. **进阶变形** [98. 验证叉搜索树](https://leetcode.com/problems/validate-binary-search-tree/)(中序遍历+单调性验证) [230. 叉搜索树中第K小的元素](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)(中序遍历计数) 3. **综合挑战** [99. 恢复叉搜索树](https://leetcode.com/problems/recover-binary-search-tree/)(中序遍历找逆序对) [173. 叉搜索树迭代器](https://leetcode.com/problems/binary-search-tree-iterator/)(迭代法中序遍历实现) --- ### 练习建议 1. 优先掌握**递归法**和**基础迭代法**的实现原理 2. 尝试用迭代法解决[98. 验证叉搜索树](https://leetcode.com/problems/validate-binary-search-tree/) 3. 在[94题](https://leetcode.com/problems/binary-tree-inorder-traversal/)提交时,对比不同解法的运行耗时 > 注:叉树节点定义通常已由题目提供,实际作答时无需重复实现 `TreeNode` 类。 [^1]: Python算法题集_叉树的中序遍历 [^2]: LeetCode94题解法参考 [^4]: 牛客网递归深度处理方案
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值