100. Same Tree同樣的樹
阿新 • • 發佈:2018-03-11
hide all ini time left solution public out 總結
[抄題]:
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:
Input: 1 1 / \ / 2 3 2 3 [1,2,3], [1,2,3] Output: true
Example 2:
Input: 1 1 / 2 2 [1,2], [1,null,2] Output: false
Example 3:
Input: 1 1 / \ / 2 1 1 2 [1,2,1], [1,1,2] Output: false
[暴力解法]:
時間分析:
空間分析:
[思維問題]:
基礎弱到沒有recursion的概念
[一句話思路]:
recursion就是嵌套
[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
- 從正反兩方面想,把所有情況都想到:p,q val相不相等,p,q不空、一個空、2個空
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
要有默認情況
[復雜度]:Time complexity: O(n) Space complexity: O(n)
所有的點走一遍,時間復雜度就是n
[英文數據結構或算法,為什麽不用別的數據結構或算法]:
[關鍵模板化代碼]:
[其他解法]:
非遞歸,用stack,很麻煩 屬於沒事找事
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
/** * 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) { //both are null if (p == null && q == null) return true; //just one null if (p == null || q == null) return false; //recursion if (p.val == q.val) return (isSameTree(p.left, q.left)) && (isSameTree(p.right, q.right)); } }View Code
100. Same Tree同樣的樹