binary-tree-preorder-traversal二叉树的前序遍历

代码:

package com.niuke.p7;

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    
    public ArrayList<Integer> preorderTraversal (TreeNode root) {
        // write code here
        ArrayList<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        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;
    }

}

 

posted @ 2020-05-31 01:04  alittlecomputer  阅读(68)  评论(0编辑  收藏  举报