二叉树的前序遍历非递归

it2022-05-05  138

class Solution { public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<>(); List<Integer> list = new ArrayList<>(); TreeNode cur = root; TreeNode top = null; while (cur != null || !stack.empty()){ while (cur != null){ System.out.print(cur.val+" "); list.add(cur.val); stack.push(cur); cur = cur.left; } top = stack.pop(); cur = top.right; } return list; } }

最新回复(0)