[LeetCode] binary-tree-preorder-traversal

来源:互联网 发布:冷漠没有同情心知乎 编辑:程序博客网 时间:2024/06/03 10:41

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].

Note: Recursive solution is trivial, could you do it iteratively?


import java.util.ArrayList;import java.util.Stack;public class Tree {public class TreeNode{int val;TreeNode left;TreeNode right;TreeNode(int x){val = x;}}public TreeNode init(){TreeNode root = new TreeNode(1);//1初始化根root.left = null;root.right = new TreeNode(2);//2初始化根的右子树root.right.left = new TreeNode(3);root.right.right = null;//返回根节点return root;}public static void main(String[] args){TreeNode root = new Tree().init();System.out.println(preorderTravelsal(root));}public static ArrayList<Integer> preorderTravelsal(TreeNode root){ArrayList<Integer> list = new ArrayList<>();if (root == null) {return list;}//使用栈结构进行存储,因为是先进后出,所以除了一开始根入栈外,后续的入栈顺序是右→左,这样弹出时即为前序遍历的顺序Stack<TreeNode> stack = new Stack<>();stack.push(root);while(!stack.isEmpty()){TreeNode t = stack.pop();list.add(t.val);if (t.right != null) {stack.push(t.right);}if (t.left != null) {stack.push(t.left);}}return list;}}