迭代统一遍历二叉树
本文最后更新于624 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com


题目链接/文章讲解:https://programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E7%BB%9F%E4%B8%80%E8%BF%AD%E4%BB%A3%E6%B3%95.html

CPP

#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>

using namespace std;

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>res;
        stack<TreeNode*>st;
        
        if(root != NULL)st.push(root);
        TreeNode *node = st.top();
        while(!st.empty()){
            st.pop();
            if(node != NULL){
                if(node->right)st.push(node->right);
                st.push(node);
                st.push(NULL);
                if(node->left)st.push(node->left);
            }else{
                st.pop();
                node = st.top();
                st.pop();
                res.push_back(node->val);
            }
        }
        return res;
    }
};
int main() {
    // 构建二叉树
    TreeNode* root = new TreeNode(1);
    root->right = new TreeNode(2);
    root->right->left = new TreeNode(3);

    // 创建 Solution 对象并调用 inorderTraversal 函数
    Solution solution;
    vector<int> result = solution.inorderTraversal(root);

    // 输出结果
    cout << "中序遍历结果: ";
    for (int val : result) {
        cout << val << " ";
    }
    cout << endl;

    // 释放内存
    delete root->right->left;
    delete root->right;
    delete root;

    return 0;
}

文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇
Cream_dpl