leetcode-94:Binary Tree Inorder Traversal (Java)
Binary Tree Inorder Traversal
Binary Tree Inorder Traversal
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.List; import java.util.ArrayList; import java.util.Stack; public class Solution { // 非递归 public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode curNode = root; while( !stack.isEmpty() || curNode!=null){ while(curNode != null){ stack.push(curNode); curNode = curNode.left; } if( !stack.isEmpty()){ curNode = stack.pop(); list.add(curNode.val); curNode = curNode.right; } } return list; } /**递归调用 public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); inorder(root,list); return list; } public void inorder(TreeNode root,List<Integer> list){ if(root == null) return; if(root.left != null){ inorder(root.left,list); } list.add(root.val); // print(root.val); if(root.right != null){ inorder(root.right,list); } } */ }