首页 > 编程语言 > 详细

LeetCode94 BinaryTreeInorderTraversal Java题解(递归 迭代)

时间:2015-07-08 13:04:35      阅读:227      评论:0      收藏:0      [点我收藏+]

题目:

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;
		  
		  
	        
	    }



版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode94 BinaryTreeInorderTraversal Java题解(递归 迭代)

原文:http://blog.csdn.net/u012249528/article/details/46799559

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!