leetcode OJ -Binary Tree Postorder Traversal(2014.1.20)
遞歸方法:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void postOrder(TreeNode* root, vector<int> &path)
{
if(root!=NULL)
{
postOrder(root->left, path);
postOrder(root->right, path);
path.push_back(root->val); //添加標記位
}
}
vector<int> postorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> path;
postOrder(root, path);
return path;
}
};
非遞歸方法:
**
* 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> path;
if(root==NULL) return path;
stack<TreeNode*> stk;
stk.push(root);
TreeNode* cur = NULL;
while(!stk.empty())
{
cur = stk.top();
if(cur->left ==NULL && cur->right ==NULL) //爲何會存在除了葉子節點還有別的節點符合這個要求
{
path.push_back(cur->val);
stk.pop();
}else{
if(cur->right)
{
stk.push(cur->right);
cur->right = NULL; //在此處進行了處理,爲了便於輸出
}
if(cur->left)
{
stk.push(cur->left);
cur->left = NULL;
}
}
}
return path;
}
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.