Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

 

return [1,2,3].

思路:递归和迭代。

//递归
class Solution {
public:
    void help(vector<int>& res, TreeNode* root)
    {
        if (!root) return;
        res.push_back(root->val);
        help(res, root->left);
        help(res, root->right);
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        help(res, root);
        return res;
    }
};

  

//迭代
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode *> sta;
        sta.push(root);
        while (!sta.empty())
        {
            TreeNode* cur = sta.top();
            sta.pop();
            res.push_back(cur->val);
            if (cur->right) sta.push(cur->right);
            if (cur->left) sta.push(cur->left);
        }
        return res;
    }
};

  

相关文章:

  • 2021-11-12
  • 2022-01-14
  • 2021-10-10
  • 2021-09-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-24
  • 2022-01-30
  • 2021-10-25
  • 2022-01-22
  • 2021-11-05
  • 2022-03-09
  • 2022-02-09
相关资源
相似解决方案