首页 > 代码库 > Binary Tree Postorder Traversal && Binary Tree Preorder Traversal

Binary Tree Postorder Traversal && Binary Tree Preorder Traversal

详见:剑指 Offer 题目汇总索引:第6题

Binary Tree Postorder Traversal

          

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?

注:后序遍历是较麻烦的一个,不可大意。关键两点: 1.要走到 p->left | p->right ==0, 2.每次出栈出两个结点。

/** * 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> answer;        if(root == NULL) return answer;        stack<TreeNode*> st;        st.push(root);        TreeNode *p = root;        while(p->right || p->left) {            while(p->left) { st.push(p->left); p = p->left;}            if(p->right) { st.push(p->right); p = p->right;}        }        while(!st.empty()) {            TreeNode *q = st.top(); st.pop();            answer.push_back(q->val);            if(!st.empty()) {                TreeNode *q2 = st.top();                while(q2->right && q2->right != q) {                    st.push(q2->right); q2 = q2->right;                    while(q2->left || q2->right) {                        while(q2->left){ st.push(q2->left); q2 = q2->left;}                        if(q2->right){ st.push(q2->right); q2 = q2->right;}                    }                   }            }        }        return answer;    }};

 

Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes‘ values.

For example: Given binary tree {1,#,2,3},

   1         2    /   3

 

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

/** * 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> preorderTraversal(TreeNode *root) {        vector<int> vec;        if(root == NULL) return vec;        stack<TreeNode*> st;        st.push(root);        while(!st.empty()) {            TreeNode *p = st.top(); st.pop();            vec.push_back(p->val);            if(p->right) st.push(p->right);            if(p->left) st.push(p->left);        }        return vec;    }};