树的两种非递归的先序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
void preOrder(TreeNode* root){
     
    if(root==nullptr)
        return ;
    stack<TreeNode*> st;
    st.push(root);
    while(!st.empty()){
     
        TreeNode* now=st.top();
        st.pop();
        cout<<now->val;
        if(now->right)
            st.push(root->right);
        if(now->left)
            st.push(root->left);
    }
}
void preOrder(TreeNode* root){
     
    if(root==nullptr)
        return ;
    stack<TreeNode*> st;
    while(root||!st.empty()){
     
        while(root){
     
            cout<<root->val;
            st.push(root);
            root=root->left;
        }
        root=st.top();
        st.pop();
        root=root->right;
    }
}

你可能感兴趣的:(编程题,基础算法)