[LeetCode145]Binary Tree Postorder Traversal
题目:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
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?
分类:Tree Stack
代码:二叉树非递归后序遍历
/** * 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) { stack<TreeNode*> s; vector<int> nodes; TreeNode* cur = root;//u当前访问的结点 TreeNode* lastNode = NULL;//上次访问的结点 while(cur || !s.empty()) { //一直向左走直到为空为止 while(cur) { s.push(cur); cur = cur->left; } cur = s.top(); //如果结点右子树为空或已经访问过,访问当前结点 if(cur->right == NULL || cur->right == lastNode) { nodes.push_back(cur->val); lastNode = cur; s.pop(); cur = NULL; } else cur = cur->right; } return nodes; } };