Created
July 9, 2015 02:56
-
-
Save xynophon/a5c5a98ce15ef8faa37d to your computer and use it in GitHub Desktop.
LeetCode. Binary Tree Inorder Traversal
recursive, iterative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.*; | |
| /** | |
| * Definition for a binary tree node. | |
| * public class TreeNode { | |
| * int val; | |
| * TreeNode left; | |
| * TreeNode right; | |
| * TreeNode(int x) { val = x; } | |
| * } | |
| */ | |
| public class BinaryTreeInorderTraversal { | |
| // recursive | |
| public List<Integer> inorderTraversal(TreeNode root) { | |
| List<Integer> ret = new ArrayList<>(); | |
| if(root == null) return ret; | |
| if(root.left != null) | |
| ret.addAll(inorderTraversal(root.left)); | |
| ret.add(root.val); | |
| if(root.right != null) | |
| ret.addAll(inorderTraversal(root.right)); | |
| return ret; | |
| } | |
| // iterative | |
| public List<Integer> inorderTraversal(TreeNode root) { | |
| List<Integer> ret = new ArrayList<>(); | |
| if(root == null) return ret; | |
| Stack<TreeNode> st = new Stack<>(); | |
| TreeNode p = root; | |
| while(!st.isEmpty() || p != null){ | |
| if(p != null){ | |
| st.push(p); | |
| p = p.left; | |
| }else{ | |
| TreeNode n = st.pop(); | |
| ret.add(n.val); | |
| p = n.right; | |
| } | |
| } | |
| return ret; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment