美文网首页
[leetcode] 144. Binary Tree Preo

[leetcode] 144. Binary Tree Preo

作者: 叶孤陈 | 来源:发表于2017-06-10 18:11 被阅读0次

    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

    相关文章

      网友评论

          本文标题:[leetcode] 144. Binary Tree Preo

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