LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)

翻译

给定一个二叉树,返回其中序遍历的节点的值。

例如:
给定二叉树为 {1#, 2, 3}
   1
    \
     2
    /
   3
返回 [1, 3, 2]

备注:用递归是微不足道的,你可以用迭代来完成它吗?

原文

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?

分析

虽然人家题目都说了递归是微不足道的,但咱还是先用递归写一遍吧。

/**
* 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;

    vector<int> inorderTraversal(TreeNode* root) {
        if (root != NULL) {
            inorderTraversal(root->left);
            v.push_back(root->val);
            inorderTraversal(root->right);
        }
        return v;
    }
};

接下是是时候写成迭代咯~

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> result;
        stack tempStack;
        while (!tempStack.empty() || root != NULL) {
            if (root != NULL) {
                tempStack.push(root);
                root = root->left;
            }
            else {
                root = tempStack.top();
                result.push_back((tempStack.top())->val);
                tempStack.pop();
                root = root->right;
            }
        }
        return result;
    }
};

另有两道类似的题目:

LeetCode 144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)

LeetCode 145 Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代)

你可能感兴趣的:(LeetCode)