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<int> preorderTraversal(TreeNode* root) {
        vector<int> vec;
        preOrder(root, vec);
        return vec;
    }
    //递归写法
    /*
    void preOrder(TreeNode *root, vector<int> &path)
    {
        if (root)
        {
            path.push_back(root->val);
            preOrder(root->left, path);
            preOrder(root->right, path);
        }
    }
    */
    //非递归写法
    void preOrder(TreeNode *root, vector<int> &path)
    {
        stack<TreeNode *> 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;
            }
        }
    }
};

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注