standard way to implement preorder tree travesal C++


  • 0
    H

    it is a standard way:

    class Solution {
    public:
    vector<int> preorderTraversal(TreeNode* root) {
    vector<int> ansValues;
    if(root == NULL) return ansValues;
    stack<TreeNode*> nodeStack;
    nodeStack.push(root);
    while(!nodeStack.empty())
    {
    TreeNode* nodeP = nodeStack.top();
    ansValues.push_back(nodeP->val);
    nodeStack.pop();
    if(nodeP->right) nodeStack.push(nodeP->right);
    if(nodeP->left) nodeStack.push(nodeP->left);
    }
    return ansValues;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.