/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List res = new LinkedList();
if (root == null)
return res;
visit(res, root);
return res;
}
public static void visit (List res, TreeNode root) {
if (root == null)
return;
//这是前序
res.add(root.val);
visit(res, root.left);
visit(res, root.right);
//这是中序
// visit(res, root.left);
// res.add(root.val);
// visit(res, root.right);
//这是后序
// visit(res, root.left);
// visit(res, root.right);
// res.add(root.val);
}
}
赵二的刷题日记《020》前、中、后序遍历二叉树
最新推荐文章于 2024-07-25 18:40:03 发布