二叉树的后序遍历
程序员文章站
2022-05-20 16:14:53
...
节点和树类:
public class TreeNode {
Integer value;
TreeNode left = null;
TreeNode right = null;
public TreeNode() {
}
public TreeNode(Integer val) {
this.value = val;
}
@Override
public String toString() {
return "TreeNode [value=" + value + "]";
}
}
public class Tree {
public TreeNode root;
public ArrayList result = new ArrayList();//结果集
//设置节点值
public void putData(TreeNode a, Integer b,Integer c){
if(b != null)
a.left = new TreeNode(b);
if(c != null)
a.right = new TreeNode(c);
}
}
递归实现:
public ArrayList<TreeNode> after(TreeNode node){
if(node == null ){//空树
return null;
}
after(node.left);
after(node.right);
result.add(node);
return result;
}
使用栈Stack实现:
方法1,将后序遍历结果看作是按照“根-右-左”遍历的逆序,那么用两个栈,一个栈用来储存节点,另一个储存逆序结果集,最后将逆序结果集出栈保存得到正序结果集。
public ArrayList<Integer> after(){
ArrayList<Integer> list = new ArrayList<Integer>();//最终结果集
Stack<TreeNode> temp = new Stack<TreeNode>();//储存临时
Stack<TreeNode> stack = new Stack<TreeNode>();//储存逆序结果集
if(root == null){//空树
return null;
}
TreeNode node = root;//当前节点
while(node != null || stack.size()!=0){
if(node != null){
stack.push(node);
temp.push(node);
node = node.right;
}else{
node = stack.pop();
node = node.left;
}
}
//出栈得到正序结果集
while(temp.size() !=0){
list.add(temp.pop().value);
}
return list;
}
方法2,考虑空间复杂度,不用储存结果集,立即输出遍历值。先把左子树压栈,出栈后先判断该节点是否有右子节点或右子节点已经遍历输出然后继续出栈,直到找到需要遍历的右子节点(或遍历结束)。
public ArrayList<Integer> after3(){
ArrayList<Integer> list = new ArrayList<Integer>();//最终结果集
Stack<TreeNode> stack = new Stack<TreeNode>();//临时储存
if(root == null){//空树
return null;
}
TreeNode node = root;//当前节点
TreeNode temp = root;//上一次遍历的节点
while(node != null || stack.size()!=0){
while(node != null){
stack.push(node);
node = node.left;
}
node = stack.pop();
//1.没有右子节点或右子节点已经遍历过
while(node.right == null || node.right == temp){
System.out.println(node.value);
temp = node;
node = stack.pop();
}
//2.右子节点还没遍历
stack.push(node);//先把当前节点(根)入栈保存
node = node.right;
}
return list;
}
测试代码:
@Test
public void treeTes1t(){
Tree tree = new Tree();
//设置节点值
tree.root = new TreeNode(1);
tree.putData(tree.root, 2, 3);
tree.putData(tree.root.left, 4, 5);
tree.putData(tree.root.right, 6, 7);
tree.putData(tree.root.right.right, null, 8);
tree.after(tree.root);//递归
System.out.println(tree.result);
System.out.println(tree.after());
System.out.println(tree.after3());
}
测试树:
输出结果:
[TreeNode [value=4], TreeNode [value=5], TreeNode [value=2], TreeNode [value=6], TreeNode [value=8], TreeNode [value=7], TreeNode [value=3], TreeNode [value=1]]
[4, 5, 2, 6, 8, 7, 3, 1]
4
5
2
6
8
7
3
1