题解 | #二叉树的前序遍历#(非递归_单栈)

二叉树的前序遍历

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;
        }

    }
}
全部评论

相关推荐

08-07 11:15
门头沟学院 Java
感觉他们公司效率好高,秒挂我简历然后又给我推荐了岗位让我投原批yyds
没有offer别哭好...:是的,然后我投了邮件里的链接,又秒挂了
投递米哈游等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务