标签:
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]
.
#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) {} }; vector<int> postorderTraversal(TreeNode *root) { vector<int>ResultVectorPsotorder; stack<TreeNode*>StackNode; if (root == NULL) return ResultVectorPsotorder; StackNode.push(root); TreeNode*CurNode = NULL; TreeNode* PreOutNode = NULL; while (!StackNode.empty()){ CurNode = StackNode.top(); if ((CurNode->right==NULL&&CurNode->left==NULL)|| (PreOutNode!=NULL&&(PreOutNode == CurNode->left || PreOutNode == CurNode->right))){ ResultVectorPsotorder.push_back(CurNode->val); StackNode.pop(); PreOutNode = CurNode; } else{ if (CurNode->right) StackNode.push(CurNode->right); if (CurNode->left) StackNode.push(CurNode->left); } } return ResultVectorPsotorder; }
Binary Tree Postorder Traversal
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/43562801