Description:
Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
经典的二叉树前序遍历,用递归闭着眼写。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> list; public List<Integer> preorderTraversal(TreeNode root) { list = new ArrayList<Integer>(); if(root==null) { return list; } pretraversal(root); return list; } public void pretraversal(TreeNode node) { if(node == null) return; list.add(node.val); pretraversal(node.left); pretraversal(node.right); } }
时间: 2024-10-23 19:34:09