GuoXin Li's Blog

Iteratively. 144.Binary Tree Preorder&Inorder Traversal

字数统计: 395阅读时长: 2 min
2021/02/01 Share

144. Binary Tree Preorder Traversal

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

Example 1:

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

Input: root = []
Output: []
Example 3:

Input: root = [1]
Output: [1]
Example 4:

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

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

Follow up: Recursive solution is trivial, could you do it iteratively?

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
/**
* 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> preorderTraversal(TreeNode* root) {
vector<int> res;
if (root == nullptr) {
return res;
}

stack<TreeNode*> stk;
TreeNode* node = root;
while (!stk.empty() || node != nullptr) {
while (node != nullptr) {
res.emplace_back(node->val);
stk.emplace(node);
node = node->left;
}
if(!stk.empty()){
node = stk.top();
stk.pop();
node = node->right;
}
}
return res;
}
};

Iterative Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void PreOrderTraversal(BinTree BT){
BinTree T = BT;
Stack S = CreatStack(Maxsize); //建立一个堆栈 S
While(T || !IsEmpty(S)){ //当 T 存在或者 S 非空时,S 为空时说明退完了
while(T){ //当 T 存在时
Push(S,T);
printf("%5d", T->Data);
T = T->Left;
}
if(!IsEmpty(S)){ //如果 S 非空
T = S.top();
S.pop();
T = T->Right;
}
}
}

difference with Inorder traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void PreOrderTraversal(BinTree BT){
BinTree T = BT;
Stack S = CreatStack(Maxsize); //建立一个堆栈 S
While(T || !IsEmpty(S)){ //当 T 存在或者 S 非空时,S 为空时说明退完了
while(T){ //当 T 存在时
Push(S,T);
T = T->Left;
}
if(!IsEmpty(S)){ //如果 S 非空
T = S.top();
printf("%5d", T->Data);
S.pop();
T = T->Right;
}
}
}
CATALOG
  1. 1. 144. Binary Tree Preorder Traversal