[LeetCode] 144. Binary Tree Preorder Traversal
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
二叉树的前序遍历。
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
思路
树的几种遍历,网上有一个不错的例子,一个树给了多种遍历的结果。
二叉树的遍历有多种方式,此题是要求用先序遍历。先序遍历的特点是根 - 左 - 右。即如果只有一个根节点和两个子节点的情形下(比如[1, 2, 3]),输出结果应该也是[1, 2, 3]。这题迭代和递归都需要掌握。遍历的时候会用到栈,因为栈是先进后出,所以放进栈的时候记得要逆向,先放右孩子再放左孩子,这样弹出的时候就会先弹出左孩子,再弹出右孩子。两种做法的时间复杂度是O(n),空间复杂度是O(h)。h是树的高度。
复杂度
时间O(n)
空间O(h)
代码
迭代
Java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
res.add(cur.val);
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
return res;
}
}
递归
Java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
helper(res, root);
return res;
}
private void helper(List<Integer> res, TreeNode root) {
if (root == null) return;
res.add(root.val);
helper(res, root.left);
helper(res, root.right);
}
}