leetcode 二叉树前序遍历的递归和非递归实现

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].

/**
 * 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 preorderTraversal(TreeNode* root) {
        vector vec;
        preOrder(root, vec);
        return vec;
    }
    //递归写法
    /*
    void preOrder(TreeNode *root, vector &path)
    {
        if (root)
        {
            path.push_back(root->val);
            preOrder(root->left, path);
            preOrder(root->right, path);
        }
    }
    */
    //非递归写法
    void preOrder(TreeNode *root, vector &path)
    {
        stack TreeNodeStack;
        
        while (root != NULL || !TreeNodeStack.empty())
        {
            while (root != NULL)
            {
                path.push_back(root->val);
                TreeNodeStack.push(root);
                root = root->left;
            }
            if (!TreeNodeStack.empty())
            {
                root = TreeNodeStack.top();
                TreeNodeStack.pop();
                root = root->right;
            }
        }
    }
};


你可能感兴趣的:(算法)