leetcode-94. Binary Tree Inorder Traversal 二叉树的中序遍历

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,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

思路:

第一种:当然就是递归,但是很慢

/**
 * 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) {
        if(!root) return {};
        vector<int> vec;
        inorder(root,vec);
        return vec;
    }
    void inorder(TreeNode* root,vector<int> & vec)
    {
        if(!root) return ;
        inorder(root->left,vec);
        vec.push_back(root->val);
        inorder(root->right,vec);
    }
};

第二种:非递归,题目要求。 非递归就是用栈一个个将元素放进去,然后 读出来

/**
 * 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) {
        if(!root) return {};
        stack<TreeNode*> s;
        vector<int> vec;
        TreeNode* p = root;
        while(p || !s.empty())
        {
            if(p)
            {
                s.push(p);
                p=p->left;
            }else
            {
                p = s.top();
                s.pop();
                vec.push_back(p->val);
                p=p->right;
            }
        }
        return vec;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_21997625/article/details/86623603