Given two binary trees, write a function to check if they are the same or not.node
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.ide
Example 1:this
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: trueExample 2:spa
Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: falseExample 3:orm
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false
相同的樹。題意是給兩個樹,判斷他們是否相同。有兩種思路,bfs和dfs。bfs是按層遍歷tree,將每層的node塞進queue而後彈出比較,須要注意塞進queue的順序。此處我只實現了dfs的作法。ip
時間O(n)it
空間O(n)io
JavaScript實現function
1 /** 2 * @param {TreeNode} p 3 * @param {TreeNode} q 4 * @return {boolean} 5 */ 6 const isSameTree = function(p, q) { 7 // corner case 8 if (p == null && q == null) return true; 9 if (p == null || q == null) return false; 10 11 // normal case 12 if (p.val == q.val) { 13 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 14 } 15 return false; 16 };
Java實現class
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public boolean isSameTree(TreeNode p, TreeNode q) { 18 if (p == null && q == null) 19 return true; 20 if (p == null || q == null) 21 return false; 22 if (p.val != q.val) 23 return false; 24 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 25 } 26 }
相關題目