c++二叉树遍历

参考文献

数据结构c语言版,严蔚敏_吴伟民著。

二叉树

c++二叉树遍历_第1张图片

中序遍历代码实现

#include
#include
using namespace std;

//Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x),left(left), right(right) {}
};
 
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) 
    {
        vector<int> ans;
        if (root == nullptr) return ans;

        if (root->left != nullptr) {
            vector<int> ansLeft = inorderTraversal(root->left);     
            for (auto item : ansLeft) {
                ans.push_back(item);
            }
        }
        ans.push_back(root->val);
        
        if (root->right != nullptr) {
            vector<int> ansRight = inorderTraversal(root->right);
            for (auto item : ansRight) {
                ans.push_back(item);
            }
        }

        return ans;
    }
};

int main()
{
    Solution s;
    TreeNode root(1);
    TreeNode node2(2);
    TreeNode node3(3);
    TreeNode node4(4);
    TreeNode node5(5);
    TreeNode node6(6);
    TreeNode node7(7);
    TreeNode node8(8);
    TreeNode node9(9);
    TreeNode node10(10);
    TreeNode node11(11);
    
    root.left = &node2;
    root.right = &node3;
    node2.left = &node4;
    node2.right = &node5;
    node3.left = &node6;
    node3.right = &node7;
    node5.left = &node8;
    node5.right = &node9;
    node9.left = &node10;
    node9.right = &node11;


    vector<int> ans = s.inorderTraversal(&root);
    for (auto item : ans) {
        cout << item << " ";
    }
    cout << endl;

    return 0;
}

结果

c++二叉树遍历_第2张图片

你可能感兴趣的:(c++数据结构,c++,算法,开发语言)