Binary Tree Postorder Traversal
来源:互联网 发布:淘宝客默认佣金是多少 编辑:程序博客网 时间:2024/05/19 18:38
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?
递归解法:
class Solution {public: void postorderRecursive(TreeNode *node, vector<int> &result) { if(node==NULL) { return ; } postorderRecursive(node->left, result); postorderRecursive(node->right, result); result.push_back(node->val); }public: vector<int> postorderTraversal(TreeNode *root) { vector<int> result; postorderRecursive(root, result); return result; }};
非递归解法:
/** * 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> result; stack<TreeNode *> stack_tree; TreeNode *currentNode = root; while(currentNode!=NULL) { stack_tree.push(currentNode); currentNode = currentNode->left; } TreeNode *currentNode2; while(!stack_tree.empty()) { currentNode = stack_tree.top(); if(currentNode->right==NULL) { result.push_back(currentNode->val); stack_tree.pop(); } else { currentNode2 = currentNode->right; currentNode->right = NULL; //关键所在 //stack_tree.push(currentNode); while(currentNode2!=NULL) { stack_tree.push(currentNode2); currentNode2 = currentNode2->left; } } } return result; }};
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
- iOS MD5字符串加密
- 理解ThreadPoolExecutor源码(二)execute函数的巧妙设计和阅读心得
- JS打印打印制定区域内容
- 【ThinkingInC++】33、构造函数和析构函数的各种特征
- 【程序员应该知道的】硬盘基本知识
- Binary Tree Postorder Traversal
- Zookeeper集群搭建
- 2014华为机试题---字符压缩
- 网站RSS的使用
- A. Boredom
- 基于Grunt构建一个JavaScript库
- 最大流问题
- GDB 内存断点
- “E576: viminfo: 缺少 '>' 位于行: ” 或者是“ E576: viminfo: Missing '>' in line: ”