本文共 779 字,大约阅读时间需要 2 分钟。
使用迭代方法先序遍历二叉树。例子:
二叉树先序遍历的迭代实现,使用栈。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public ListpreorderTraversal(TreeNode root) { List res = new ArrayList<>(); if (root == null) return res; ArrayList stack = new ArrayList<>(); while (root != null || !stack.isEmpty()) { if (root == null) { root = stack.remove(stack.size() - 1).right; } else { stack.add(root); res.add(root.val); root = root.left; } } return res; }}
很基础的一个题。
转载地址:http://xxesi.baihongyu.com/