1.将树的前序和中序遍历进行了格式上的统一,方便大家的记忆
2.树的后序遍历是左右根,是根右左的逆序,树的先序遍历是根左右,改成树的遍历是根右左即可,再翻转
树的前序遍历
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new LinkedList<>();
TreeNode p=root;
Stack<TreeNode> stack=new Stack<>();
while(!stack.isEmpty()|| p!=null)
{
while(p!=null)
{
stack.push(p);
res.add(p.val);
p=p.left;
}
if(!stack.isEmpty())
{
p=stack.pop();
p=p.right;
}
}
return res;
}
树的中序遍历
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new LinkedList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode p=root;
while(!stack.isEmpty()|| p!=null)
{
while(p!=null)
{
stack.push(p);
p=p.left;
}
if(!stack.isEmpty())
{
p=stack.pop();
res.add(p.val);
p=p.right;
}
}
return res;
}
后序遍历
public void reverse(List<Integer> l)
{
for(int i=0;i<l.size()/2;i++)
{
int temp=l.get(i);
l.set(i,l.get(l.size()-1-i));
l.set(l.size()-1-i,temp);
}
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res=new LinkedList<>();
if(root==null)
return res;
TreeNode p=root;
Stack<TreeNode> stack=new Stack<>();
while(!stack.isEmpty()|| p!=null)
{
while(p!=null)
{
stack.push(p);
res.add(p.val);
p=p.right;
}
if(!stack.isEmpty())
{
p=stack.pop();
p=p.left;
}
}
reverse(res);
return res;
}