主页 Preorder, Inorder and Postorder Traversal of a Binary Tree
Post
Cancel

Preorder, Inorder and Postorder Traversal of a Binary Tree

Preface

This article has a strong personal flavor; if it makes you uncomfortable, please close it right away. This article is only for personal study notes. You’re welcome to repost or share it within the scope of the license agreement, but please respect the copyright and keep the original link. Thank you for your understanding and cooperation. If you find this site helpful, you can subscribe via RSS. Thanks for the support!

As the title says

Given the root node root of a binary tree, return its preorder, inorder, and postorder traversals.

Example 1

1
2
输入:root = [1,null,2,3]
输出:[1,2,3]

Example 2

1
2
输入:root = []
输出:[]

Example 3

1
2
输入:root = [1]
输出:[1]

Implementation Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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:
    void inorder(TreeNode *root, vector<int> &res) {
        if (!root) {return;}
        
        //Preorder
        res.push_back(root->val);
        preorder(root->left,res);
        preorder(root->right,res);

        //Inorder
        inorder(root->left, res);
        res.push_back(root->val);
        inorder(root->right,res);

        //Postorder
        postorder(root->left, res);
        postorder(root->right, res);
        res.push_back(root->val);
    }

    vector<int> inorderTraversal(TreeNode* root) {
        vector <int> ans;
        inorder(root, ans);
        return ans;
    }
};

144. Binary Tree Preorder Traversal
94. Binary Tree Inorder Traversal
145. Binary Tree Postorder Traversal
Quoted from codetop

该博客文章由作者通过 CC BY 4.0 进行授权。