问题描述
- Given a binary tree, return the inorder traversal of its nodes’ values.
- Follow up: Recursive solution is trivial, could you do it iteratively?
- 地址
问题分析
代码实现
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorderTraversal(root, res);
return res;
}
public void inorderTraversal(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
inorderTraversal(root.left, res);
res.add(root.val);
inorderTraversal(root.right, res);
}
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<Integer>();
}
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curNode = root;
while (curNode != null || ! stack.isEmpty()) {
while (curNode != null) {
stack.push(curNode);
curNode = curNode.left;
}
curNode = stack.pop();
res.add(curNode.val);
curNode = curNode.right;
}
return res;
}
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<Integer>();
}
List<Integer> res = new ArrayList<>();
Stack<Command> stack = new Stack<>();
stack.push(new Command(false, root));
while(! stack.isEmpty()) {
Command curCommand = stack.pop();
TreeNode curRoot = curCommand.root;
if (curCommand.isPrint) {
res.add(curRoot.val);
}else {
if (curRoot.right != null) {
stack.push(new Command(false, curRoot.right));
}
stack.push(new Command(true, curRoot));
if (curRoot.left != null) {
stack.push(new Command(false, curRoot.left));
}
}
}
return res;
}
class Command{
boolean isPrint;
TreeNode root;
public Command(boolean isPrint, TreeNode root) {
this.isPrint = isPrint;
this.root = root;
}
}