LeetCode刷題筆記(2)——Tree篇

LeetCode刷題筆記(2)——Tree篇

接上一篇,本篇主要記錄Tree分類下的相關習題。

目錄

94. Binary Tree Inorder Traversal
96. Unique Binary Search Trees
100. Same Tree
101. Symmetric Tree
104. Maximum Depth of Binary Tree

94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
在這裏插入圖片描述
Output: [1,3,2]

分析:本題需要中序遍歷二叉樹,並將結果返回到List中。有兩種方法。
  第一種方法是使用遞歸的思想,這裏需要一個helper函數,可以存儲每次遞歸返回的結果。對於每個非空節點,依次遞歸遍歷它的左孩子、當前節點的值、遞歸遍歷它的右孩子。helper函數其中的一個輸入參數爲當前的list。
  第二種方法是在棧的幫助下使用迭代,而不利用遞歸。
   1.令根節點爲當前節點t,將當前節點t壓棧。
   2.若當前節點t存在左孩子,也將左孩子壓棧,並將左孩子置爲當前節點t。
   3.循環執行2,直至當前節點無左孩子,當前節點t出棧,並在list中記錄當前節點的val值。
   4.若當前節點t存在右孩子,將右孩子壓棧,並將右孩子置爲當前節點t。否則棧頂元素出棧,該棧頂元素被置爲當前節點t。
   5.重複執行2-4,直至棧空爲止。

優化的代碼如下:

第一種方法:遞歸

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        helper(root,list);
        return list;
    }
    private void helper(TreeNode root,List<Integer> list){
        if(root != null){
            helper(root.left,list);
            list.add(root.val);
            helper(root.right,list);
        }
    }
}

第二種方法:迭代

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode t = root;
        while(t != null || !stack.isEmpty()){
            while(t != null){
                stack.push(t);
                t = t.left;
            }
            t = stack.pop();
            list.add(t.val);
            t = t.right;
        }       
        return list;
    }
}

96. Unique Binary Search Trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

Example:

Input: 3
Output: 5
Explanation: Given n = 3, there are a total of 5 unique BST’s:
在這裏插入圖片描述
分析:本題求解給定節點個數,可能存在多少種不同的二叉排序樹。

優化的代碼如下:


100. Same Tree

Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:
在這裏插入圖片描述
Example 2:
在這裏插入圖片描述
Example 3:
在這裏插入圖片描述
分析:本題有兩種方法,第一種方法是使用遞歸的思想,如果兩個節點都是空節點返回true,如果兩個節點中一個爲空另一個非空返回false,如果兩個節點的val值不等返回false,如果兩個節點都非空並且val值相等,遞歸求解兩個節點的左孩子是否相等,兩個節點的有孩子是否相等。
   第二種方法是在隊列的幫助下使用迭代,而不利用遞歸。隊列中的每兩個連續節點應該相等,並且它們的子樹也相等。首先將當前兩個節點加入到隊列,如果當前兩節點對象非空並且val值相等,將第一個節點的左孩子、第二個節點的左孩子、第一個節點的右孩子、第二個節點的右孩子依次加入到隊列中。循環取隊頭的兩個節點比較,若出現不相等則不是相同的樹,返回false。

優化的代碼如下:

第一種方法:遞歸

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null && q != null || (p != null && q ==null)) return false;
        if(p.val != q.val) return false;
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}

第二種方法:迭代

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        Queue<TreeNode> list = new LinkedList<>();
        list.add(p);
        list.add(q);
        while(!list.isEmpty()){
            TreeNode t1 = list.poll();
            TreeNode t2 = list.poll();
            if(t1==null && t2==null) continue;
            if(t1==null && t2!=null || (t1!=null && t2==null)) return false;
            if(t1.val!=t2.val) return false;
            list.add(t1.left);
            list.add(t2.left);
            list.add(t1.right);
            list.add(t2.right);
        }
        return true;
    }
}

101. 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:
在這裏插入圖片描述
But the following [1,2,2,null,3,null,3] is not:
在這裏插入圖片描述
Note:
Bonus points if you could solve it both recursively and iteratively.

分析:類似於第100題,本題有兩種方法。與之不同的是,本題是判斷是否爲對稱樹,對稱樹要求根節點的左孩子p與根節點右孩子q應相等,並且p的左孩子與q的右孩子相等,同時p的右孩子與q的左孩子相等。因此,第一種方法的遞歸中,最後應遞歸求解節點的左孩子是否等於另一個節點的右孩子且節點的右孩子是否等於另一個節點的左孩子。第二種方法的迭代中,在往隊列中加入元素時,順序也應相應的改變。應當依次加入第一個節點的左孩子、第二個節點的右孩子、第一個節點的右孩子、第二個節點的左孩子,然後以同樣的方法判斷隊列中相鄰的兩個節點是否相等。

優化的代碼如下:

第一種方法:遞歸

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return isMirror(root.left,root.right);
    }
    private boolean isMirror(TreeNode p, TreeNode q){
    	if(p == null && q == null) return true;
        if(p == null && q != null || (p != null && q == null)) return false;
        if(p.val != q.val) return false;
        return isMirror(p.left,q.right) && isMirror(p.right,q.left);
    }
}

第二種方法:迭代

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue <TreeNode> list = new LinkedList<>();
        list.add(root);
        list.add(root);
        while(!list.isEmpty()){
            TreeNode t1 = list.poll();
            TreeNode t2 = list.poll();
            if(t1==null && t2==null) continue;        
            if(t1==null && t2!=null || (t1!=null && t2==null)) return false;
            if(t1.val != t2.val) return false;
            list.add(t1.left);
            list.add(t2.right);
            list.add(t1.right);
            list.add(t2.left);
        }
        return true;
    }
}

104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],
在這裏插入圖片描述
return its depth = 3.

分析:本題求解樹的高度,使用遞歸的方法。當根節點爲空時,返回0。否則遞歸求解左子樹的深度與右子樹深度的最大值,最大值加1即爲該樹的高度。

優化的代碼如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }else{
            return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
        }            
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章