二叉树的三种遍历——非递归法

二叉树的三种遍历我们都知道有 前序遍历、中序遍历和后序遍历。

对于这三种遍历的递归写法,我们会觉得十分好理解,但是发现对于其非递归写法还是认为很复杂。所以就记录于此,希望有一天都能凭借自己本事写出来。加油~

    List<Integer> res = new ArrayList<Integer>();

	/**
	 * 前序遍历 非递归 写法
	 * @param node
	 */
	public List<Integer> beforeOrder(Node root) {
		if(root == null) 
			return res;
		Stack<Node> stack = new Stack<Node>();
		//将根节点入栈
		stack.push(root);
		//若栈非空,则继续循环
		while(!stack.isEmpty()) {
			Node node = stack.pop();	//根结点出栈
			res.add(node.data);
			//因为栈遵循“先进后出”原则,所以先将右孩子入栈
			if(node.rightChild != null)
				stack.push(node.rightChild);
			if(node.leftChild != null)
				stack.push(node.leftChild);
		}
		
		return res;
	}
	
	/**
	 * 中序遍历  左、中、右
	 * @param root
	 * @return
	 */
	public List<Integer> inOrder(Node root){
		if(root==null)
			return res;
		Stack<Node> stack = new Stack<Node>();
		Node node = root;
		//若栈非空或者当前结点非空
		while(!stack.isEmpty() || node!=null) {
			if(node!=null) {	//如果当前结点非空
				stack.push(node);	//入栈
				node = node.leftChild;	//指向左孩子
			} else {	//如果当前结点空,但栈非空
				node = stack.pop();	//出栈
				res.add(node.data);
				node = node.rightChild;	//指向右孩子
			}
		}
		return res;
	}
	/**
	 * 后序遍历  左、右、中
	 * @param root
	 * @return
	 */
	public List<Integer> afterOrder(Node root){
		if(root==null)
			return res;
		Stack<Node> stack = new Stack<Node>();
		stack.push(root);	//因为根节点最后遍历,所以先将根节点入栈
		//若栈非空
		while(!stack.isEmpty()) {
			Node node = stack.pop();//首先出栈的是根节点,其后先出右结点、再出左结点
			if(node.leftChild!=null)
				stack.push(node.leftChild);	//将左孩子入栈
			if(node.rightChild!=null)
				stack.push(node.rightChild);//将右孩子入栈
			//把node的值插到res首部。因为while循环中遍历顺序是中右左,插到首部后顺序就是左右中
			res.add(0, node.data);
		}
		return res;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值