Leetcode - Same Tree

来源:互联网 发布:qq视频播放器 mac 编辑:程序博客网 时间:2024/04/28 02:07

Question

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 Code

    public class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int x) { val = x; }    }    public boolean isSameTree(TreeNode p, TreeNode q) {        //对应节点都不为空        if(p != null && q != null) {            if(p.val != q.val)                return false;            else {//递归判断左右子节点,直到判断为假时返回                if(!isSameTree(p.left, q.left)) return false;                if(!isSameTree(p.right, q.right)) return false;                return true;            }        }        //对应节点都为空        else if(p == null && q == null)            return true;        //对应节点中,有且仅有一个为空        else            return false;    }

说明

  • 遍历二叉树时使用深度优先搜索。
0 0
原创粉丝点击