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