Binary Tree Postorder Traversal
来源:互联网 发布:超旺软件 编辑:程序博客网 时间:2024/05/11 16:24
Question:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
Answer:/** * Definition for binary tree * 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) { stack<TreeNode *> treeStack;TreeNode * node=NULL;TreeNode * pre=root;//这个地方将pre初始化成root非常有必要,如果用NULL来初始化会出现非常严重的问题, //在入栈操作时如果root节点的子节点中有为空的节点, //那么root节点下面的节点不会进行入栈操作,其他节点也是这样。vector<int> vec;if (NULL==root){return vec;}treeStack.push(root);while(!treeStack.empty()){node=treeStack.top(); //这个地方是进行入栈操作的入口,pre表示上一个被处理的元素,最开始时总会进入这个判断,这样树中的元素会入栈。//回溯的时候当从栈treeStack中弹出的元素是上一个被处理的元素的父节点时会忽略掉下面的入栈操作if (pre!=node->left&&pre!=node->right){if (node->right){treeStack.push(node->right);//因为是后序遍历,所以右节点先入栈}if (node->left){treeStack.push(node->left);//左节点入栈}}if (node->left==NULL&&node->right==NULL//这个判断表示当前处理的节点是叶节点,那么将节点的值保存在容器中||pre==node->left||pre==node->right)//这个判断表示回溯时对非叶节点的处理,因为是回溯过程,所以也需要把节点的值保存在容器中{vec.push_back(node->val);treeStack.pop();//元素处理完后出栈}pre=node;}return vec; }};
0 0
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Cisco 3750 交换机策略路由PBR
- cisco 3550为例介绍IOS的恢复方法
- 2511密码破解
- tlplayer,wzplayer所有平台通用加密测试视频
- XP,2003下使用route命令增加永久路由(静态路由)
- Binary Tree Postorder Traversal
- 钻石戒指参数介绍
- ISATAP ( Intra-Site Automatic Tunnel Addressing Protocol
- Linux Apache php MySQL GD PHPWind 集成环境配置
- 转帖:DSG变速箱各类故障的简单解读,看了你就知道为什么会有问题了
- linux路由添加
- Python2.7环境下安装pydbg
- RedHat-Linux密码破解
- centos修改IP地址