题解 | #二叉树的前序遍历#

二叉树的前序遍历

https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635

  • 递归解法
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        // write code here
        vector<int> ans;
        pre(root, ans);
        return ans;
    }
  	void pre(TreeNode* root, vector<int> &res) {
      if(!root) return ;
      res.push_back(root->val);
      pre(root->left, res);
      pre(root->right, res);
};

  • 迭代解法
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        // write code here
        vector<int> ans;
        if(root == NULL) return ans;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()) {
            TreeNode* cc = st.top();
            st.pop();
            ans.push_back(cc->val);
            if(cc->right) st.push(cc->right);
            if(cc->left) st.push(cc->left);
        }
        return ans;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务