【LeetCode】Same Tree

来源:互联网 发布:linux查看所有服务状态 编辑:程序博客网 时间:2024/06/05 13:35

Same Tree 
Total Accepted: 8888 Total Submissions: 20908 My Submissions
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.
节前开了专栏,休了春节假期,有点懈怠。
来个简单题先练练手吧。
递归,没什么特别难的地方。
Java AC

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isSameTree(TreeNode p, TreeNode q) {        if(p != null && q != null){            if(p.val != q.val){                return false;            }            boolean lFlag = isSameTree(p.left,q.left);            boolean rFlag = isSameTree(p.right,q.right);            if(!lFlag || !rFlag){                return false;            }        }        if((p != null && q == null) || (p == null && q != null)){            return false;        }        return true;    }}
0 0
原创粉丝点击