94. Binary Tree Inorder Traversal

Problem:

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

Example:

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

Output: [1,3,2]

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

思路1

使用递归。

Solution I (C++):

public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> traverse;
        inorderTraversal(root, traverse);
        
        return traverse;
    }
private:
    void inorderTraversal(TreeNode *root, vector<int> &traverse) {
        if (!root)  return;
        
        inorderTraversal(root->left, traverse);
        traverse.push_back(root->val);
        inorderTraversal(root->right, traverse);
    }

性能

Runtime: 4 ms  Memory Usage: 9.3 MB

思路2

使用利用栈的迭代。

Solution II (C++):

vector<int> inorderTraversal(TreeNode* root) {
    vector<int> traverse;
    stack<TreeNode*> stk;
    
    while (root || !stk.empty()) {
        while (root) {
            stk.push(root);
            root = root->left;
        }
        root = stk.top();
        stk.pop();
        traverse.push_back(root->val);
        root = root->right;
    }
    return traverse;
}

性能

Runtime: 4 ms  Memory Usage: 9.2 MB

posted @ 2020-02-16 10:47  littledy  阅读(112)  评论(0编辑  收藏  举报