标签:binary tree postorde 二叉树 后序遍历 非递归
Q:Given a binary tree, return the postorder traversal of its nodes‘ values.
Note:Recursive solution is trivial, could you do it iteratively?
题目的意思就是不用递归求二叉树的后序遍历。
后续遍历的递归方式很简单,首先遍历左子树,然后遍历右子树,最后遍历根节点;遍历左右子树的时候,仍然是先遍历左子树,然后再遍历右子树,最后遍历根节点。非递归的时候,就额外使用递归中隐含的栈,重点注意的是,遍历右子树的时候需要做个标记,表示右子树是否已经被访问过。
下面贴上代表,便于测试正确性,补上二叉树的先序建立算法:
#include <iostream> #include <vector> #include <stack> using namespace std; struct TreeNode{ int val; TreeNode* left; TreeNode* right; TreeNode(int x) :val(x), left(NULL), right(NULL){} }; class Solution{ public: TreeNode* root; public: TreeNode* createPre(TreeNode* bt){ int x; cin >> x; if (x == 0) bt = NULL; else{ bt = new TreeNode(x); bt->left = createPre(bt->left); bt->right = createPre(bt->right); } return bt; } void create(){ root = createPre(root); } vector<int> postorderTraversal(TreeNode *root) { vector<int> order; if (root == NULL) return order; stack<TreeNode*> s; TreeNode* visited = NULL; while (root != NULL || !s.empty()){ while (root != NULL){ s.push(root); root = root->left; } root = s.top(); if (root->right == NULL || root->right==visited){ order.push_back(root->val); s.pop(); visited = root; root = NULL; } else{ root = root->right; } } return order; } };下图是测试用例,0表示左/右孩子指针为空
测试结果如下:
[LeetCode]Binary Tree Postorder Traversal
标签:binary tree postorde 二叉树 后序遍历 非递归
原文地址:http://blog.csdn.net/kaitankedemao/article/details/43340151