前序遍历二叉树,递归及非递归版本

class Solution {

public:

    vector<int> res;

    vector<int> preorderTraversal(TreeNode* root) {

        if(root == NULL) return res;

        res.push_back(root->val);

        preorderTraversal(root->left);

        preorderTraversal(root->right);

        return res;

    }

};

 

前序遍历二叉树,递归及非递归版本

 

class Solution {

public:

    vector<int> res;

    vector<int> preorderTraversal(TreeNode* root) {

        vector<int> vt;

        if(!root) return vt;

        stack<TreeNode*> st;

        st.push(root);

        TreeNode* node=NULL;

        while(!st.empty())

        {

            node=st.top();

            st.pop();

            vt.push_back(node->val);

            if(node->right) st.push(node->right);

            if(node->left) st.push(node->left);

        }

        return vt;

    }

};

 

 

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-01-12
  • 2022-02-09
  • 2022-02-19
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-27
  • 2021-07-31
  • 2022-03-04
  • 2021-12-03
  • 2021-11-21
相关资源
相似解决方案