题目描述
Given a binary tree, return the preorder traversal of its nodes’ values.

方法思路
Approach1: 递归 recursive
class Solution {
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 36.3 MB, less than 14.66%
List<Integer> res = new LinkedList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null) return res;
res.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return res;
}
}
Approach2: iteratively
class Solution{
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 36.3 MB, less than 11.50%
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
res.add(node.val);
if(node.right != null)
stack.push(node.right);
if(node.left != null)
stack.push(node.left);
}
return res;
}
}

本文介绍了一种解决二叉树前序遍历问题的两种方法:递归和迭代。递归方法通过直接调用自身实现节点的访问,而迭代方法使用栈来跟踪节点的访问顺序。
410

被折叠的 条评论
为什么被折叠?



