[leetCode]144. 二叉树的前序遍历
csdn:https://blog.csdn.net/renweiyi1487/article/details/109308919
题目
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
traverse(root, ans);
return ans;
}
private void traverse(TreeNode cur, List<Integer> ans) {
if (cur == null) {
return;
}
ans.add(cur.val);
traverse(cur.left, ans);
traverse(cur.right, ans);
}
}
迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null)
return ans;
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node != null) {
if (node.right != null)
stack.push(node.right); // 右
if (node.left != null)
stack.push(node.left); // 左
stack.push(node);
stack.push(null); // 中,要处理的节点进行标记
} else {
node = stack.pop();
ans.add(node.val);
}
}
return ans;
}
}