Binary Tree Postorder Traversal @leetcode

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)+" ");		
		}
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值