题解 | #二叉树的前序遍历#(非递归_单栈)
二叉树的前序遍历
http://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
通过使用栈,来代替递归
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
public int[] preorderTraversal (TreeNode root) {
// write code here
if (root == null) {
return new int[0];
} else {
int[] a = new int[100];
int i = 0;
Stack<TreeNode> s = new Stack<>();
s.push(root);
while (!s.empty()) {
// 先序遍历,根左右
TreeNode t = s.pop();
a[i++] = t.val;
// 先放右子树,先入后出
if (t.right != null)s.push(t.right);
if (t.left != null)s.push(t.left);
}
int[] b = Arrays.copyOf(a, i);
return b;
}
}
}