leetcode 94. 二叉树的中序遍历(DFS,InOrder)

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

code

递归版

class Solution {
public:
    vector inorderTraversal(TreeNode* root) {
        vector v;
        getnum(root, v);
        return v;
    }
    void getnum(TreeNode *root, vector & v){
        if(root){
            getnum(root->left, v);
            v.push_back(root->val);
            getnum(root->right, v);
        }  
    }
};

迭代版

class Solution {
public:
    vector inorderTraversal(TreeNode* root) {
        vector v;
        stack s;
        while(root || !s.empty()){ 
            if(root){
                s.push(root);
                root = root->left;
            }
            else{
                root = s.top();s.pop();
                v.push_back(root->val);
                root = root->right;
            }
        }
        return v;
    }
};

 

你可能感兴趣的:(acm)