天天看點

leetcode 94. Binary Tree Inorder Traversal中序周遊

我特麼要菜哭了

這玩意怎麼能卡這麼久

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]      

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

/**
 * 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>v;
    void dfs(TreeNode* root){
        if(root->left)
            dfs(root->left);
        v.push_back(root->val);
        if(root->right)
            dfs(root->right);
    }
    vector<int> inorderTraversal(TreeNode* root) {
        v.clear();
        if(root)
            dfs(root);
        return v;
    }
};
           
/**
 * 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> inorderTraversal(TreeNode* root) {
        vector<int>v;
        if(root==NULL)
            return v;
        stack<TreeNode*>s;
        s.push(root);
        while(s.size()){
            TreeNode* tmp=s.top();
            if(tmp->left){
                s.push(tmp->left);
                tmp->left=NULL;
                continue;
            }
            v.push_back(s.top()->val);
            s.pop();
            if(tmp->right){
                s.push(tmp->right);
                tmp->right=NULL;
                continue;
            }
        }
        return v;
    }
};