[leetcode] 144. Binary Tree Preorder Traversal 二叉树前序遍历

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

Note: Recursive solution is trivial, could you do it iteratively?

解题思路:

递归版:

class Solution {
public:
    void getPreorderData(TreeNode* root,vector<int> & ret)
    {
        if(root == NULL) return;
        ret.push_back(root->val);
        if(root->left) getPreorderData(root->left,ret);
        if(root->right) getPreorderData(root->right,ret);
        return;
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ret;
        getPreorderData(root,ret);
        return ret;
    }
};

迭代版:

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

参考资料:https://discuss.leetcode.com/topic/6493/accepted-iterative-solution-in-java-using-stack

    原文作者:叶孤陈
    原文地址: https://www.jianshu.com/p/a452c965580f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞