Binary Tree Traversal (C++)

之前的版本太多,这里总结一下三种非递归遍历(C++)

preorder

class Solution {
public:
    vector preorderTraversal(TreeNode* root) {
        vector result;
        stack st;
        TreeNode * p = root;
        while(!st.empty() || p) {
            if(p != NULL) {
                st.push(p);
                result.push_back(p->val);
                p = p->left;
            } else {
                TreeNode * top = st.top();
                st.pop();
                p = top->right;
            }
        }
        return result;
    }
};

inorder

class Solution {
public:
    vector inorderTraversal(TreeNode* root) {
        vector result;
        stack st;
        TreeNode * p = root;
        while(!st.empty() || p) {
            if(p != NULL) {
                st.push(p);
                p = p->left;
            } else {
                TreeNode * top = st.top();
                st.pop();
                result.push_back(top->val);
                p = top->right;
            }
        }
        return result;
    }
};

postorder

class Solution {
public:
    vector postorderTraversal(TreeNode* root) {
        vector result;
        stack st;
        TreeNode * p = root;
        TreeNode * pre = NULL;
        while(!st.empty() || p) {
            if(p != NULL) {
                st.push(p);
                p = p->left;
            } else {
                TreeNode * top = st.top();
                if(top->right == NULL || top->right == pre) {
                    st.pop();
                    pre = top;
                    result.push_back(top->val);
                } else {
                    p = top->right;
                }
            }
        }
        return result;
    }
};

你可能感兴趣的:(Binary Tree Traversal (C++))