递归
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null) return new ArrayList<Integer>();
List<Integer> list = new ArrayList<Integer>();
preorderTraversal(root, list);
return list;
}
public List<Integer> preorderTraversal(TreeNode root, List<Integer> list) {
if(root.left != null)
preorderTraversal(root.left, list);
list.add(root.val);
if(root.right != null)
preorderTraversal(root.right, list);
return list;
}
迭代
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
LinkedList<Integer> output = new LinkedList<>();
if (root == null) {
return output;
}
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
output.addFirst(node.val);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
return output;
}
网友评论