DAY15——二叉树part2

层序遍历模板(使用队列实现)

class Solution {
    public List> levelOrder(TreeNode root) {
        List> list = new ArrayList>();
        layerTraverse(root, list);
        return list;
    }

    public void layerTraverse(TreeNode root, List> list){
        if(root == null){  //null直接返回
            return;
        }
        Queue q = new LinkedList();
        q.offer(root);
        while(! q.isEmpty()){
            List tempList = new ArrayList();
            int len = q.size();
            while(len>0){
                TreeNode tmpNode = q.poll();
                tempList.add(tmpNode.val);

                if(tmpNode.left!=null)  q.offer(tmpNode.left);
                if(tmpNode.right!=null) q.offer(tmpNode.right);
                len--;
            }
            list.add(tempList);
        }
        
    }
}

 翻转二叉树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        swapNode(root);
        invertTree(root.left);
        invertTree(root.right);
        
        return root;
    }

    public void swapNode(TreeNode root) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
        
}

    

判断二叉树是否对称

DAY15——二叉树part2_第1张图片

使用递归法 

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left, root.right);
    }

    private boolean compare(TreeNode left, TreeNode right) {

        if (left == null && right != null) {
            return false;
        }
        if (left != null && right == null) {
            return false;
        }

        if (left == null && right == null) {
            return true;
        }
        if (left.val != right.val) {
            return false;
        }
        // 比较外侧
        boolean compareOutside = compare(left.left, right.right);
        // 比较内侧
        boolean compareInside = compare(left.right, right.left);
        return compareOutside && compareInside;
    }
}

除去四种if的遍历情况,就是left和right值相等,此时进行后续的compare比较。

你可能感兴趣的:(leetcode,java,算法)