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?
递归的不说了。记得本科数据结构的书里讲过了非递归的实现方式,需要自己手写一个stack。Preorder是三种DFS里最好实现的,每个node都是在第一次被从stack中pop出来后就进行访问。
逻辑:
1.把root放到stack里
2.从stack里pop出一个node,进行访问
3.右儿子放到Stack里
4.左儿子放到stack里
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null)
return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(node.val);
if(node.right != null)
stack.push(node.right);
if(node.left != null)
stack.push(node.left);
}
return result;
}
}