leetcode 原题地址:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
后序遍历思想:访问左孩子--》访问右孩子--》访问根节点
递归思想的完整代码如下:
package tree;
import java.util.ArrayList;
public class Postorder_traversal {
private TreeNode root = null;
private ArrayList<Integer> res;
public Postorder_traversal(){
root = new TreeNode(1,1);
}
//创建二叉树
public void createBinaryTree(TreeNode root){
TreeNode newNodeB = new TreeNode(2,2);
TreeNode newNodeC = new TreeNode(3,3);
root.rightChild = newNodeB;
root.rightChild.leftChild = newNodeC;
}
//二叉树由结点构成,所以需要创建TreeNode类
public class TreeNode{
private int key = 0;
private int data = 0;
private TreeNode leftChild = null;
private TreeNode rightChild = null;
public TreeNode(int key,int data){
this.key = key;
this.data = data;
this.leftChild = null;
this.rightChild = null;
}
}
//二叉树结点通常用数组或线性表进行存储,这里选择使用数组ArrayList才存储
public ArrayList<Integer> preorder_Traversal(TreeNode root){
res = new ArrayList<Integer>();
helper(root,res);
return res;
}
public void helper(TreeNode root,ArrayList<Integer> res){
if (root == null)
return ;
else {
//访问左孩子--》访问右孩子--》访问根结点
helper(root.leftChild,res);
helper(root.rightChild,res);
res.add(root.data);
}
}
public static void main(String[] args){
Postorder_traversal bt = new Postorder_traversal();
bt.createBinaryTree(bt.root);
bt.preorder_Traversal(bt.root);
int count = bt.res.size();
System.out.println("****先序遍历****");
for (int i=0;i<count;i++){
System.out.print(bt.res.get(i)+" ");
}
}
}