To start with, i will give the LeetCode Link!
- 94. Binary Tree Inorder Traversal
- 144. Binary Tree Preorder Traversal
- 145. Binary Tree Postorder Traversal
I only solve them with the recursive method!
I give my code below!
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
helper(root, result);
return result;
}
private void helper(TreeNode root, List<Integer> result){
if (root == null) return;
helper(root.left, result);
result.add(root.val);
helper(root.right, result);
}
}
It is Inorder. If want to use the preorder or postorder, just change the sequence of these clause!
helper(root.left, result);
result.add(root.val);
helper(root.right, result);
What's more, some excellent coder give more innovative solution!