这是一道将二叉树先序遍历,题目不难,采用深搜
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public static List<Integer> resultlist = new ArrayList<Integer>(); public static void dfs (TreeNode root ,boolean flag ) { if(flag==true) { resultlist.clear(); } if(root==null) { return ; } resultlist.add(root.val); if(root.left!=null) { dfs(root.left,false); } if(root.right!=null) { dfs(root.right,false); } } public static List<Integer> preorderTraversal(TreeNode root ) { dfs(root,true); return resultlist; } }
时间: 2024-11-03 21:37:21