题目地址:https://leetcode.com/problems/binary-tree-inorder-traversal/description/
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?
既然不让用递归,那就只能用堆栈了。
public class BinaryTreeInorderTraversal {
public static List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null)
return res;
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (node != null) {
stack.push(node);
node = node.left;
}
while (!stack.isEmpty()) {
node = stack.pop();
res.add(node.val);
if (node.right != null) {
node = node.right;
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
return res;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.right = new TreeNode(2);
root.right.left = new TreeNode(3);
System.out.println(inorderTraversal(root));
return;
}
}