Leetcode - Tree - Easy(100-110)

CocoaPuff發表於2020-12-31
  1. Same Tree
    Given the roots of two binary trees p and q, write a function to check if they are the same or not.
/**
 * 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 boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null && q==null){return true;}
        if(p==null || q==null){return false;}
        if(p.val!=q.val){return false;} 

        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}
  1. Symmetric Tree
    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return isSymmetricHelper(root,root);
    }
    private boolean isSymmetricHelper(TreeNode t1,TreeNode t2){
        if(t1==null && t2==null){return true;}
        if(t1==null || t2==null){return false;}
        if(t1.val!=t2.val){return false;}
        return isSymmetricHelper(t1.left,t2.right) && isSymmetricHelper(t1.right,t2.left);
    }
}
  1. Maximum Depth of Binary Tree
class Solution {
    public int maxDepth(TreeNode root) {
        return root==null? 0 : Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }
}
  1. Binary Tree Level Order Traversal
    Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

/**
 * BFS思路, queue用來記錄每層要處理的節點,levelList記錄本層節點
 */
class Solution1 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root==null){return result;}
        
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            List<Integer> levelList = new ArrayList<>();
            int levelCount = q.size();
            
            for(int i=0;i<levelCount;i++){
                TreeNode tmp = q.poll();
                levelList.add(tmp.val);
                if(tmp.left!=null){
                    q.offer(tmp.left);
                }
                if(tmp.right!=null){
                    q.offer(tmp.right);
                }
            }
            
            result.add(levelList);
        }
        return result;
    }
}
/**
 * DFS思路,巧妙之處在於每新增一個ArrayList,result的大小就會加1。
 * 後面再訪問到本層時就不再增加新ArrayList,而是直接在本層的ArrayList中加元素。
 */
class Solution2 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        levelOrderHelper(result,root,0);
        return result;
    }
    private void levelOrderHelper(List<List<Integer>> result,TreeNode node,int level){
        if(node==null){return;}
        if(result.size()==level){ 
            result.add(new ArrayList<Integer>());
        }
        result.get(level).add(node.val);
        levelOrderHelper(result,node.left,level+1);
        levelOrderHelper(result,node.right,level+1);
    }
}
  1. Binary Tree Level Order Traversal II
    For example:
    Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]

/**
 *BFS和上題思路一樣,但用Linkedlist.addFirst()方法就可以改輸出順序
 */
class Solution1 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<>();
        if(root==null){return result;}
        
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            List<Integer> tmp = new ArrayList<>();
            int size = q.size();
            for(int i=0;i<size;i++){
                TreeNode node = q.poll();
                tmp.add(node.val);
                if(node.left!=null){
                    q.offer(node.left);
                }
                if(node.right!=null){
                    q.offer(node.right);
                }
            }
            result.addFirst(tmp);
        }
        return result;
    }
}

/**
*DFS和上題思路一樣,注意result.get到第幾層List
*/

class Solution2 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<>();
        levelOrderBottomHelper(result,root,0);
        return result;
    }
    private void levelOrderBottomHelper(LinkedList<List<Integer>> result, TreeNode root, int level){
        if(root==null){return;}
        if(result.size()==level){
            result.addFirst(new ArrayList<Integer>());
        }
        result.get(result.size()-level-1).add(root.val);
        levelOrderBottomHelper(result,root.left,level+1);
        levelOrderBottomHelper(result,root.right,level+1);
    }
}
  1. Convert Sorted Array to Binary Search Tree
    Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
    Example:
    Given the sorted array: [-10,-3,0,5,9],
    One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
      0
     / \
   -3   9
   /   /
 -10  5
/**
 * BFS,找到中間節點再遞迴構建左右
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0){return null;}
        return createBST(nums,0,nums.length-1);
    }
    private TreeNode createBST(int[] nums, int begin, int end){
        if(begin>end){return null;}
        int mid=begin + (end-begin)/2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left=createBST(nums,begin,mid-1);
        node.right=createBST(nums,mid+1,end);
        return node;
    }
}
  1. Balanced Binary Tree
    Given a binary tree, determine if it is height-balanced.
    For this problem, a height-balanced binary tree is defined as:
    a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
    下面這個就不是BBT
       0
     /   \
   -3     9
   /     /
 -8    5
 /    
-10  
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null){return true;}
        if(Math.abs(maxDepth(root.left)-maxDepth(root.right)) > 1){return false;}
        return isBalanced(root.left) && isBalanced(root.right);
    }
    
    private int maxDepth(TreeNode root){
        return root==null? 0: Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }
}

相關文章