二叉树1

144.二叉树的前序遍历
class Solution {
    public List preorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        if(root==null) return res;
        Stack stack = new Stack<>();
        stack.add(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            res.add(node.val);
            if(node.right!=null){
                stack.push(node.right);
            }
            if(node.left!=null){
                stack.push(node.left);
            }
        }
        return res;
    }
}
102.二叉树的层次遍历
class Solution {
    public List> levelOrder(TreeNode root) {
        List> res = new ArrayList<>();
        if(root==null) return res;
        Queue queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List list = new ArrayList<>();
            for(int i=0;i

你可能感兴趣的:(二叉树1)