反復は二叉木の先序、中序、後序遍歴(c+)を実現する.

12979 ワード

ツリーの定義
/**
 * 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> preorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL) return res;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()){
            TreeNode* top=st.top();
            st.pop();
            res.push_back(top->val);
            if(top->right!=NULL) st.push(top->right);//      ,                
            if(top->left!=NULL) st.push(top->left);
        }
        return res;
    }
};

ちゅうかんじゅんかん遍歴
反復
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL) return res;
        stack<TreeNode*> st;
        TreeNode* cur=root;
        while(!st.empty()||cur!=NULL){
            while(cur!=NULL){//       
                st.push(cur);
                cur=cur->left;
            }
            cur=st.top();
            st.pop();
            res.push_back(cur->val);
            cur=cur->right;
        }
        return res;
    }
};

あとじゅんかん遍歴
反復
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL) return res;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()){
            TreeNode* top=st.top();
            st.pop();
            res.push_back(top->val);
            if(top->left!=NULL) st.push(top->left);//      ,              ,            
            if(top->right!=NULL) st.push(top->right);
        }
        reverse(res.begin(),res.end());
        return res;
    }
};