LeetCode刷題100. Same Tree
阿新 • • 發佈:2018-12-14
題目:
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
思路解析:
判斷兩棵樹是不是同一棵樹,需要判斷每個節點都相同。由於樹這種特殊的結構,解答樹有關的問題通常需要用遞迴來實現,本題也不例外。
首先判斷兩棵樹是否都為空,都為空返回true;
既然第一步已經判斷兩顆樹是否都為空,接下來只需要判斷其中有一顆為空就可以直接返回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){ return false; } if(p.val == q.val){ return isSameTree(p.left,q.left) && isSameTree(p.right,q.right); } return false; } }