[Leetcode]Binary Tree Inorder Traversal

来源:互联网 发布:cs1.6 fps优化 编辑:程序博客网 时间:2024/06/11 04:38

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,3,2].

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

class Solution {public:    /*algorithm: recuisvie     */    void inorderSub(TreeNode* root,vector<int>&path){        if(!root)return;        inorderSub(root->left,path);        path.push_back(root->val);        inorderSub(root->right,path);    }    vector<int> inorderTraversal(TreeNode* root) {            vector<int>path;            inorderSub(root,path);            return path;    }};
class Solution {public:    /*algorithm: iterative     */    vector<int> inorderTraversal(TreeNode* root) {            vector<int>path;            if(!root)return path;            stack<TreeNode*>stk;            unordered_set<TreeNode*>S;            stk.push(root);            while(!stk.empty()){                TreeNode* t = stk.top();                while(t->left && !S.count(t->left)){                    stk.push(t->left);                    S.insert(t->left);                    t = t->left;                }                path.push_back(t->val);                stk.pop();                if(t->right)stk.push(t->right);            }            return path;                }};



0 0
原创粉丝点击