[LeetCode] 100. Same Tree
阿新 • • 發佈:2017-09-30
bin ref leet for tco pst com lee 傳送門
傳送門
Description
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
思路
題意:給出兩棵二叉搜索樹,判斷這兩棵二叉搜索樹是否相同
題解:前序遍歷+中序遍歷或後序遍歷+中序遍歷可以完全確定一顆二叉搜索樹(數據中第52組:[1,null,1] [1,1],此種寫法掛在了這裏);或者直接遞歸搜索的過程判斷。
/** * 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); else return false; } }
[LeetCode] 100. Same Tree