leetcode Binary Tree Inorder| Preorder| Postorder

Preorder

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

Inorder

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

Postorder  

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        if(root)
        {  
             if(root->left)  postorderTraversal(root->left);
             if(root->right) postorderTraversal(root->right);
             res.push_back(root->val);
        }
    }
    
    vector<int> postorderTraversal(TreeNode *root) {
        
        vector<int> res;
        stack<TreeNode *> st;
        
        while()
    }
};




你可能感兴趣的:(LeetCode,preorder,Inorder,postorder)