Binary Tree Preorder Traversal Problem


Description

LeetCode Problem 144.

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

Example 1:

1
2
Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2:

1
2
Input: root = []
Output: []

Example 3:

1
2
Input: root = [1]
Output: [1]

Example 4:

1
2
Input: root = [1,2]
Output: [1,2]

Example 5:

1
2
Input: root = [1,null,2]
Output: [1,2]

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100


Sample C++ 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
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> preorder;
        
        if (root == NULL)
            return preorder;
        
        stack<TreeNode*> s;
        s.push(root);
        TreeNode* tp;
        
        while (!s.empty()) {
            tp = s.top();
            s.pop();
            if (tp == NULL)
                continue;
            s.push(tp->right);
            s.push(tp->left);
            preorder.push_back(tp->val);
        }
        return preorder;
    }
};




Related Posts

Binary Tree Preorder Traversal Problem

LeetCode 144. Given the root of a binary tree, return...

Binary Tree Postorder Traversal Problem

LeetCode 145. Given the root of abinary tree, return the...

Path Sum II Problem

LeetCode 113. Given the root of a binary tree and...