1 对于后序遍历来说我们可以用栈来保存根节点,但是出栈的时候必须判断,先前遍历的节点来自左节点还是右节点,这里用r保存先前遍历的节点
首先给出树节点结构的定义:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
后序遍历代码为:
class Solution {
private:
vector<int> res;
public:
vector<int> postorderTraversal(TreeNode* root) {
if(root==NULL)
return res;
stack<TreeNode*> st;
TreeNode *p=root;
TreeNode *r=NULL;
while(p||st.size())
{
if(p)
{
st.push(p);
p=p->left;
}
else
{
p=st.top();
if(p->right&&p->right!=r)
{
p=p->right;
st.push(p);
p=p->left;
}
else
{
res.push_back(p->val);
r=st.top();
st.pop();
p=NULL;
}
}
}
return res;
}
};
对于中序后后序来说比较简单
中序代码为:
class Solution {
private:
vector<int> res;
public:
vector<int> inorderTraversal(TreeNode* root) {
if(root==NULL)
return res;
stack<TreeNode *> st;
TreeNode *p=root;
while(p||st.size())
{
if(p)
{
st.push(p);
p=p->left;
}
else
{
p=st.top();
st.pop();
res.push_back(p->val);
p=p->right;
}
}
return res;
}
};
先序代码:
public class Solution {
public List<Integer> preorderTraversal(TreeNode node) {
List<Integer> list = new LinkedList<Integer>();
Stack<TreeNode> rights = new Stack<TreeNode>();
while(node != null) {
list.add(node.val);
if (node.right != null) {
rights.push(node.right);
}
node = node.left;
if (node == null && !rights.isEmpty()) {
node = rights.pop();
}
}
return list;
}
}