首页 > 其他 > 详细

【手撕】中序遍历二叉树

时间:2020-12-27 15:22:29      阅读:30      评论:0      收藏:0      [点我收藏+]
#include<iostream>
#include<vector>
#include<stack>

using namespace std;

struct TreeNode // 定义树节点的结构
{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};


/*
class Solution // 中序遍历二叉树,迭代解法
{
public:
    vector<int> result;
    vector<int> preorderTraversal(TreeNode* root) // 中序遍历二叉树,返回的是数组
    {
        if (root == nullptr)
        {
            return {};
        }
        preorderTraversal(root->left);
        result.push_back(root->val);
        preorderTraversal(root->right);

        return result;
    }
};
*/

class Solution //递归解法
{
public:
    vector<int> preorderTraversal(TreeNode* root)
    {
        stack<TreeNode*> sta;
        vector<int> result;
        if (root == nullptr)
        {
            return {};
        }
        TreeNode* cur = root;
        while (cur != nullptr || !sta.empty())
        {
            if (cur != nullptr)
            {
                sta.push(cur);
                cur = cur->left;
            }
            else
            {
                cur = sta.top();
                sta.pop();
                result.push_back(cur->val);
                cur = cur->right;
            }
        }
        
        return result;
    }
};

int main()
{
    TreeNode* node1 = new TreeNode(1);
    TreeNode* node2 = new TreeNode(2);
    TreeNode* node3 = new TreeNode(3);
    node1->right = node2;
    node2->left = node3;
    TreeNode* root = node1;
    
    vector<int> res;
    Solution solution;
    res = solution.preorderTraversal(root);

    vector<int>::iterator iter = res.begin();
    while (iter != res.end())
    {
        cout << *iter << endl;
        iter++;
    }

    return 0;
}

 

【手撕】中序遍历二叉树

原文:https://www.cnblogs.com/masbay/p/14197155.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!