LeetCode Problem Link: https://leetcode.com/problems/binary-tree-inorder-traversal
Solution:
[1] Recursive
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if (root == null) return result;
result.addAll(inorderTraversal(root.left));
result.add(root.val);
result.addAll(inorderTraversal(root.right));
return result;
}
}
[2] Iterative (using stack for DFS search)
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> nodeStack = new Stack();
TreeNode cur = root;
while (cur != null || !nodeStack.empty()) {
while (cur != null) {
nodeStack.add(cur);
cur = cur.left;
}
cur = nodeStack.pop();
result.add(cur.val);
cur = cur.right;
}
return result;
}
}
Result:
Run time 2 ms
Beats 25% users
Solution:
[1] Recursive
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if (root == null) return result;
result.addAll(inorderTraversal(root.left));
result.add(root.val);
result.addAll(inorderTraversal(root.right));
return result;
}
}
[2] Iterative (using stack for DFS search)
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> nodeStack = new Stack();
TreeNode cur = root;
while (cur != null || !nodeStack.empty()) {
while (cur != null) {
nodeStack.add(cur);
cur = cur.left;
}
cur = nodeStack.pop();
result.add(cur.val);
cur = cur.right;
}
return result;
}
}
Result:
Run time 2 ms
Beats 25% users
留言
張貼留言