给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[1,2]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
// return preorderTraversalI(root);
// return preorderTraversalII(root);
return preorderTraversalIII(root);
}
//方法三:迭代II
//时间复杂度O(N),空间复杂度O(N)
private List<Integer> preorderTraversalIII(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
//将跟节点入栈
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
list.add(node.val);
//分别将右子树和左子树压栈,这样出栈的顺序则为从左到右
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return list;
}
//方法二:迭代I
//时间复杂度O(N),空间复杂度O(N)
private List<Integer> preorderTraversalII(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
//先添加根节点,不断遍历左子树
while (!stack.isEmpty() || root != null) {
while (root != null) {
list.add(root.val);
stack.push(root);
root = root.left;
}
//遍历到叶子节点时,出栈
root = stack.pop();
//回到右子树,继续遍历
root = root.right;
}
return list;
}
//方法一:递归
//时间复杂度O(N),空间复杂度O(N)
private List<Integer> preorderTraversalI(TreeNode root) {
List<Integer> list = new ArrayList<>();
helper(root, list);
return list;
}
private void helper(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
helper(root.left, list);
helper(root.right, list);
}
}