Binary Tree Postorder Traversal
2015-09-08 16:55
169 查看
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?
题意:
后续遍历
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?
题意:
后续遍历
/** * 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) { vector<int> path; if(root==NULL)return path; stack<TreeNode*> stk; stk.push(root);//将根节点入栈 TreeNode* cur = NULL; while(!stk.empty())//如果栈非空 { cur = stk.top();//将cur指向当前栈首。 //如果左右子树为空, if(cur->left ==NULL && cur->right ==NULL) { path.push_back(cur->val);//如果左右子树都处理过,就表示栈为空 stk.pop(); }else{ if(cur->right)//如果存在右子树,这里先右子树入栈。 { stk.push(cur->right); cur->right = NULL;//表示根节点右子树处理 } if(cur->left)//如果存在左子树。 { stk.push(cur->left); cur->left = NULL;//表示跟节点左子树处理过 } } } return path; } };
相关文章推荐
- Freemarker自定义方法
- poj 1017
- Cannot create JDBC driver of class '' for connect URL 'null'
- Mac添加命令别名
- Android 百度地图 SDK v3.0.0 (二) 定位与结合方向传感器
- jquery动态移除/增加onclick属性详解
- [Bootstrap]7天深入Bootstrap(2)整体架构
- 织梦系统与discuz论坛整合方法
- 笔记-大话设计模式-13 建造者模式
- html上汉字乱码解决
- hdfs体系
- LeetCode 11_Container With Most Water
- Linux shell脚本的字符串截取
- The import org.apache.commons.codec cannot be resolved
- hdu5428
- Hibernate – One-to-Many example (Annotation)
- KL散度
- java 长整除问题
- scala中 object 和 class的区别
- 苹果IOS开发者账号的区别,企业账号,个人账号,公司团队账号,教育账号