LeetCode94 BinaryTreeInorderTraversal Java题解(递归 迭代)

题目:

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [1,3,2].

解题:

中序遍历一颗二叉树,如果是递归就很简单了,中序遍历左+访问根节点+中序遍历右 就可以了。迭代的话,我是通过一个栈,从根节点开始入栈,只要一直存在左节点就一直入栈,不存在左节点就出栈访问节点值,然后继续遍历出栈那个节点的右节点。

代码:

1,递归

	public static List<Integer> result=new ArrayList<>();
	  public static List<Integer> inorderTraversal(TreeNode root,List<Integer> result) {
		  if(root!=null)
		  {
			  inorderTraversal(root.left,result);
			  result.add(root.val);
			  inorderTraversal(root.right,result);
		  }
		  
		  return result;
		  
	        
	    }
	  
2,迭代(下面两个函数都是  只是不同的写法而已)

 public static List<Integer> inorderTraversal2(TreeNode root,List<Integer> result) {
		  List<Integer> res=new ArrayList<>();
		  Stack<TreeNode> nodeStack=new Stack<>();
		  
		 
		  while(root!=null||!nodeStack.isEmpty())
		  {
			  while(root!=null)
			  {
				  nodeStack.push(root);
				  root=root.left;
			  }
			  
			  TreeNode tempNode=nodeStack.pop();
			  res.add(tempNode.val);
			  root=tempNode.right;
			  
		  }
		  return res;
		  
		  
	        
	    }
	  
	  public static List<Integer> inorderTraversal3(TreeNode root,List<Integer> result) {
		  List<Integer> res=new ArrayList<>();
		  Stack<TreeNode> nodeStack=new Stack<>();
		  
		 
		 while(true)
		 {
			 while(root!=null)
			 {
				 nodeStack.add(root);
				 root=root.left;
			 }
			 
			 if(nodeStack.isEmpty()) break;
			 
			 TreeNode tempNode=nodeStack.pop();
			 res.add(tempNode.val);
			 root=tempNode.right;
		 }
		 
		 return res;
		  
		  
	        
	    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值