二叉树的遍历

 

二叉树的定义

/**
 * 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> result;
        stack<TreeNode*> my_stack;
        if(root == NULL) return result;
        my_stack.push(root);
        while(!my_stack.empty()){
            TreeNode* cur_node = my_stack.top();
            my_stack.pop();
            result.push_back(cur_node->val);
            if(cur_node->right != NULL){
                my_stack.push(cur_node->right);
            }
            if(cur_node->left != NULL){
                my_stack.push(cur_node->left);
            } 
        }
        return result;
    }   
};

中序遍历

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> my_stack;
        if(root == NULL) return result;
        //my_stack.push(root);
        auto cur = root;
        while(!my_stack.empty() || cur != NULL){
            
                while(cur != NULL){
                    my_stack.push(cur);
                    cur = cur->left;
                }
                auto node = my_stack.top();
                result.push_back(node->val);
                my_stack.pop();
                if(node->right != NULL){
                    cur = node->right;
                }
        }
        return result;
    }   
};

后序遍历

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> my_stack;
        if(root == NULL) return result;
        my_stack.push(root);
        while(!my_stack.empty()){
            TreeNode* cur_node = my_stack.top();
            my_stack.pop();
            result.push_back(cur_node->val);
            if(cur_node->left != NULL){
                my_stack.push(cur_node->left);
            } 
            if(cur_node->right != NULL){
                my_stack.push(cur_node->right);
            }
        }
        std::reverse(result.begin(),result.end()); //反转vector
        return result;
    }   
};