递归方法实现二叉树其实很简单,其实只需要更改输出每个结果与·调用递归函数的相对位置即可实现。
一、递归实现
1.二叉树的前续遍历
class Solution {
private:
void rec(TreeNode* root,vector<int> &ret){
if(root != NULL){
ret.push_back(root->val);
rec(root->right,ret);
rec(root->left,ret);
}
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
rec(root,ret);
return ret;
}
};
2.二叉树的中续遍历
class Solution {
private:
void rec(TreeNode* root,vector<int> &ret){
if(root != NULL){
rec(root->right,ret);
ret.push_back(root->val);
rec(root->left,ret);
}
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
rec(root,ret);
return ret;
}
};遍历**
3.二叉树的后续遍历
class Solution {
private:
void rec(TreeNode* root,vector<int> &ret){
if(root != NULL){
rec(root->right,ret);
rec(root->left,ret);
ret.push_back(root->val);
}
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
rec(root,ret);
return ret;
}
};
可以看到,我们只是修改 ret.push_back(root->val);
这行代码的位置。
二、二叉树遍历的非递归实现
按照正常的解法,可以按照如下链接的代码进行求解:
二叉树的前序遍历
二叉树的中序遍历
二叉树的后续遍历
但是上述代码差异性较大,有没有可能采用类似递归那种统一的方法实现二叉树的三种遍历呢?
那么首先,我们需要了解一下递归的实现方式:
递归调用的过程相当于将函数的形参和局部变量在系统的栈中进行压栈和弹出的过程。
递归调用与栈
所以我们可以定义一个结构体来实现递归调用中系统的栈的功能。
结构体包含,进行的操作的指示,go表示应该继续进行遍历,print表示可以输出该节点的信息。
struct Command{
string s; //go:继续遍历 print:打印
TreeNode* node;
Command(string s,TreeNode* node): s(s),node(node){}
};
有了Command结构体,然后我们可以定义栈stack<Command>
,接下来我们就可以对二叉树的结点进行遍历操作了,需要注意的是,我们是采用栈的操作,所有进行前序遍历的时候最后再把要进行print操作的节点放入栈中。
完整代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct Command{
string s; //go:继续遍历 print:打印
TreeNode* node;
Command(string s,TreeNode* node): s(s),node(node){}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
if(root == NULL) return ret;
stack<Command> st;
st.push(Command("go",root));
while(!st.empty()){
Command command = st.top();
st.pop();
if(command.s == "print")
ret.push_back(command.node->val);
else{
st.push(Command("print",command.node));
if(command.node->right != NULL)
st.push(Command("go",command.node->right));
if(command.node->left != NULL)
st.push(Command("go",command.node->left));
}
}
return ret;
}
};