码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode94 BinaryTreeInorderTraversal Java题解(递归 迭代)

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

标签:迭代   递归   inordertraversal   binarytree   leetcode   

题目:

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题解(递归 迭代)

标签:迭代   递归   inordertraversal   binarytree   leetcode   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!