首页 > 代码库 > leetcode 94 Binary Tree Inorder Traversal ----- java
leetcode 94 Binary Tree Inorder Traversal ----- java
Given a binary tree, return the inorder traversal of its nodes‘ values.
For example:
Given binary tree [1,null,2,3]
,
1 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
求二叉树的中序遍历,要求不是用递归。
先用递归做一下,很简单。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List result = new ArrayList<Integer>(); public List<Integer> inorderTraversal(TreeNode root) { if( root == null) return result; getResult(root); return result; } public void getResult(TreeNode root){ if( root.left != null) getResult(root.left); result.add(root.val); if( root.right != null) getResult(root.right); } }
不用递归,用栈实现也是很简单的。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List result = new ArrayList<Integer>(); public List<Integer> inorderTraversal(TreeNode root) { if( root == null) return result; Stack stack = new Stack<TreeNode>(); TreeNode node = root; while( true ){ if( node.left == null){ result.add(node.val); if( node.right == null ){ if( stack.isEmpty() ) break; else node = (TreeNode) stack.pop(); }else{ node = node.right; } }else{ TreeNode flag = node; node = node.left; flag.left = null; stack.push(flag); } } return result; } }
leetcode 94 Binary Tree Inorder Traversal ----- java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。