Preorder
Preorder
题目地址
题目描述
Given a binary tree, return the preorder traversal of its nodes' values.
The first data is the root node, followed by the value of the left and right son nodes, and "#" indicates that there is no child node.
The number of nodes does not exceed 20.代码
Approach #1 No-Recursion
public class Solution {
public List<Integer> preorderTraverl(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<IInteger> preorder = new ArrayList<Interger>();
if (root == null) {
return preorder;
}
stack.push(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
preorder.add(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return preorder;
}
}Approach #2 Traverse
Approach #3 Divide & Conquer
Last updated
Was this helpful?