题解 | #求二叉树的前序遍历#

求二叉树的前序遍历

https://www.nowcoder.com/practice/501fb3ca49bb4474bf5fa87274e884b4

import java.util.*;
public class Solution {
    ArrayList<Integer> list = new ArrayList<Integer>();
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        if(root == null)
            return list;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode temp = stack.pop();
            list.add(temp.val);
            if(temp.right != null)
                stack.push(temp.right);
            if(temp.left != null)
                stack.push(temp.left);
        }
        return list;
    }
}
全部评论

相关推荐

522090231:差评,我要让每一届都吃上这种苦头😡
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务