题目:
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; } };
本文介绍了一种非递归方法实现二叉树的后序遍历,通过使用栈来跟踪节点,避免了传统的递归方法。文章详细解释了算法的流程,包括如何处理左右子树以及访问根节点的顺序。

被折叠的 条评论
为什么被折叠?



