LeetCode144 Binary Tree PreOrder Traversal Java question (recursive iteration)
Question:
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].
Solution:
The idea of traversing a binary tree in sequence is similar to that in the previous article. Just give it to the code.
Recursion:
public static List
reslut=new ArrayList<>();public static List
preorderTraversal(TreeNode root) {if(root!=null) {reslut.add(root.val);preorderTraversal(root.left);preorderTraversal(root.right);}return reslut; }
Iteration:
public static List
preorderTraversal2(TreeNode root) {List
res=new ArrayList<>();Stack
nodeStack=new Stack<>();while(true){while(root!=null){res.add(root.val);nodeStack.push(root);root=root.left;}if(nodeStack.isEmpty()) break;TreeNode tempNode=nodeStack.pop();root=tempNode.right;}return res; }