美文网首页
144.binary-tree-preorder-travers

144.binary-tree-preorder-travers

作者: Optimization | 来源:发表于2020-05-10 09:58 被阅读0次

迭代算法,用到了栈

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if(root == nullptr)
            return {};
        vector<int> ans;
        stack<TreeNode*> s;
        TreeNode* curNode = root;
        s.push(root);
        while(!s.empty()){
          TreeNode* n =  s.top();s.pop();
          ans.push_back(n->val);
          if(n->right != nullptr) s.push(n->right);
          if(n->left != nullptr) s.push(n->left);
        }
        return ans;
    }


};

相关文章

网友评论

      本文标题:144.binary-tree-preorder-travers

      本文链接:https://www.haomeiwen.com/subject/djbdnhtx.html