【LeetCode】 144. Binary Tree Preorder Traversal 二叉树的前序遍历(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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]
Example 4:
Input: root = [1,2]
Output: [1,2]
Example 5:
Input: root = [1,null,2]
Output: [1,2]
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?
题目大意
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解题方法
1.1 采用递归方法
递归算法非常简单,前序遍历,只需要把 root.val 先输出即可
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
pH(root, list);
return list;
}
public void pH(TreeNode root, List<Integer> list) {
if (root == null) return;
list.add(root.val);
if (root.left != null) pH(root.left, list);
if (root.right != null) pH(root.right, list);
}
}
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:36.6 MB,击败了94.43% 的Java用户
1.2 进阶:采用循环方法
循环方法比递归稍稍难一些
- 用一个列表把树节点存起来
- 取出最前面的节点,然后把“右节点”,“左节点”依次放到最前面的节点(因为下一次还是需要取左节点,所以需要先放右节点,再放左节点,这样左节点就在最前面)
- 不断循环,直到没有节点为止
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
List<TreeNode> nodeList = new ArrayList<>();
nodeList.add(root);
while (nodeList.size() > 0) {
TreeNode cur = nodeList.remove(0);
list.add(cur.val);
if (cur.right != null) nodeList.add(0, cur.right);
if (cur.left != null) nodeList.add(0, cur.left);
}
return list;
}
}
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:36.6 MB,击败了94.10% 的Java用户