给出一棵二叉树,返回其节点值的前序遍历。
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,2,3]
.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* 维护一个栈,将根节点入栈,然后只要栈不为空,出栈并访问,接着依次将访问节点的右节点、左节点入栈。
* 这种方式应该是对先序遍历的一种特殊实现(看上去简单明了),但是不具备很好的扩展性,在中序和后序方式中不适用
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root){
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
//先保存根结点
stack.push(root);
while(!stack.empty()){
TreeNode head = stack.pop();
list.add(head.val);
//先右进栈
if(head.right != null){
stack.push(head.right);
}
//再左进栈
if(head.left != null){
stack.push(head.left);
}
}
return list;
}
}