一、前序遍历
递归解法:
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector preorderTraversal(TreeNode *root) {
vector val_vec;
traverse(root, val_vec);
return val_vec;
}
private:
void traverse(TreeNode *root, vector &ret) {
if (root == NULL) {
return;
}
ret.push_back(root->val);
traverse(root->left, ret);
traverse(root->right, ret);
}
};
非递归解法:
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector preorderTraversal(TreeNode *root) {
vector val_vec;
stack s;
if (root == NULL) {
return val_vec;
}
s.push(root);
while (!s.empty()) {
const TreeNode *node = s.top();
s.pop();
val_vec.push_back(node->val);
if (node->right != NULL) {
s.push(node->right);
}
if (node->left != NULL) {
s.push(node->left);
}
}
return val_vec;
}
};
二、中序遍历
递归解法:
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector inorderTraversal(TreeNode *root) {
vector result;
traverse(root, result);
return result;
}
private:
void traverse(TreeNode *root, vector &ret) {
if (root == NULL) {
return;
}
traverse(root->left, ret);
ret.push_back(root->val);
traverse(root->right, ret);
}
};
非递归解法:
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector inorderTraversal(TreeNode *root) {
vector result;
stack s;
while (!s.empty() || NULL != root) {
if (root) {
s.push(root);
root = root->left;
} else {
root = s.top();
s.pop();
result.push_back(root->val);
root = root->right;
}
}
return result;
}
};
三、后序遍历
递归解法:
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector postorderTraversal(TreeNode *root) {
vector result;
traverse(root, result);
return result;
}
private:
void traverse(TreeNode *root, vector &ret) {
if (root == NULL) {
return;
}
traverse(root->left, ret);
traverse(root->right, ret);
ret.push_back(root->val);
}
};
非递归解法:
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
stack<TreeNode*> s;
vector<int> res;
vector<bool> flag(1000);
int i = 0;
while (!s.empty() || root!=NULL) {
if (root) {
s.push(root);
flag[i++] = 0;
root = root->left;
} else if (flag[i-1]==0) {
root = s.top();
root = root->right;
flag[i-1] = 1;
} else {
TreeNode* tmp = s.top();
res.push_back(tmp->val);
s.pop();
i--;
}
}
return res;
}
};