题目


解答
先序排序
先判断根节点是否为空
在判断左节点是否为空
在判断有节点是否为空
依次迭代
ArrayList<Integer> result = new ArrayList<>();
public ArrayList<Integer> preorderTraversal(TreeNode root) {
// write code here
if (root == null) {
return result;
} else {
result.add(root.val);
if (root.left != null) {
preorderTraversal(root.left);
}
if (root.right != null) {
preorderTraversal(root.right);
}
}
return result;
}
本文详细介绍了二叉树的先序遍历算法,通过递归方式实现节点的访问,首先访问根节点,然后左子树,最后右子树。使用Java语言展示了先序遍历的具体代码实现。
78

被折叠的 条评论
为什么被折叠?



