145. Binary Tree Postorder Traversal 树后续遍历 flag方法和reverse方法
来源:互联网 发布:问答系统源码 编辑:程序博客网 时间:2024/06/05 10:17
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> postorderTraversal(TreeNode* root) { vector<int> ans; stack<TreeNode*> s; TreeNode* cur = root; TreeNode* last = NULL; while(cur || !s.empty()){ if(cur){ s.push(cur); cur = cur->left; }else{ TreeNode* topNode = s.top(); if(topNode->right && last != topNode->right){//栈顶节点有右子树,且右子树没被访问过 cur = topNode->right; //s.push(cur); 这个地方就不要push了 }else{ ans.push_back(topNode->val); last = topNode; s.pop(); } } } return ans; }};
reverse方法:
public List<Integer> postorderTraversal(TreeNode root) { LinkedList<Integer> result = new LinkedList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); result.addFirst(p.val); // Reverse the process of preorder p = p.right; // Reverse the process of preorder } else { TreeNode node = stack.pop(); p = node.left; // Reverse the process of preorder } } return result;}
0 0
- 145. Binary Tree Postorder Traversal 树后续遍历 flag方法和reverse方法
- leetcode 145. Binary Tree Postorder Traversal 二叉树后续遍历
- Binary Tree Postorder Traversal 二叉树后续遍历@LeetCode
- 【二叉树的后续遍历】Binary Tree Postorder Traversal
- leetcode---binary-tree-postorder-traversal---树后续遍历
- leetcode 145. Binary Tree Postorder Traversal-后续遍历|递归|非递归
- 二叉树遍历145. Binary Tree Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal (利用中序遍历和后续遍历确定一颗二叉树)
- LeetCode 145 Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代)
- 145.Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 逻辑推理 - 归纳推理
- php笔记
- Eclipse启动tomcat无法访问的解决方法
- 用python做自动化测试--web 自动化测试(1)-Selenium 3.x使用系列问题集
- 关于字符串的逆序题目
- 145. Binary Tree Postorder Traversal 树后续遍历 flag方法和reverse方法
- 单片机LCD简单多级菜单实现
- 【论文笔记】Sequence to sequence Learning with Neural Networks
- SecureCRT 7.0 安装破解版指导
- uC/OS_II操作系统的软件体系结构。
- 时间记录
- Java基础学习笔记:(一)概述
- python实现一个完整的blog网站
- Git/Github使用笔记(一)——如何生成SSH key及访问Github