二叉树前序遍历,分为递归方法和非递归方法:
递归:
private static List<Integer> preList = new ArrayList<>(); public static List<Integer> preorderTraversalRec(TreeNode root){ if (null == root){ return preList; } preorder(root); return preList; } private static void preorder(TreeNode root){ if (null == root){ return; } preList.add(root.val); preorder(root.left); preorder(root.right); }
非递归:
public static List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); if (null == root){ return list; } Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()){ TreeNode node = stack.pop(); list.add(node.val); if (null != node.right){ stack.push(node.right); } if (null != node.left){ stack.push(node.left); } } return list;
}