算法与数据结构_树_二叉树中序遍历的三种方法

刷leetcode碰到了二叉树的中序遍历,提供了三种方法,在这里记录一下。

  1. 常规的递归方法
public List<Integer> inorderTraversal_1(TreeNode root){
	List<Integer> res = new ArrayList<Integer>();
	recursion(res,node);
	return node;
}
public void recursion(List<Integer> res,TreeNode node){
	if(node!=null){
		recursion(res,node.left);
		res.add(node.val);
		recursion(res,node.right);
	}
}
  1. 常规的栈储存方法
public List<Integer> inorderTraversal_2(TreeNode root){
	List<Integer> res = new ArrayList<Integer>();
	Stack<TreeNode> stack =new Stack<TreeNode>();
	while(root!=null || !stack.isEmpty()){
	 //先把左边的全部放进去
		while(root!=null){
			stack.push(root);
			root=root.left;
		}
		//取出最左边的
		root = stack.pop();
		res.add(root.val);
		//再放入右边的
        //两种情况:
       	// 1. 有右孩子,将右孩子和右孩子的所有左子树放入stack
        // 2. 没有右孩子,将root变为null,就不会走里层开头的while,
        //	  防止将root循环放入
		root = root.right;
	}
}
  1. 特别的Morrirs方法
public List<Integer> inorderTraversal_3(TreeNode root){
	List<Integer> res = new ArrayList<Integer>();
	TreeNode = temp;//临时变量
	while(root!=null){
		if(root.left!=null){
			temp = root.left;
			while(temp.right!=null && temp.right != root){
				temp = temp.right;
			}
			// 将右孩子与root相连
			//这样“已经到了最左边,没有左孩子”的情况(即下方的while)
			//root=root.right可以直接返回上层的根节点
			if(temp.right == null){
				temp.right = root;
				root = root.left;
			}else{
			// 说明已经连过了,并且下面的树已经走完
			// 只有走完了,才会由root = root.right再次返回到这个节点
            //首先将连接消除,然后将值加入列表,最后访问右孩子
            	temp.right = null;
				res.add(root.val);
				root = root.right;
			}
		}else{
			res.add(root.val);
			root = root.right;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值