相同的樹

/**
 * 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) {
        //p 和q是兩個數的根節點
        if(p == null && q!=null) {
            return false;
        }
        if(p != null && q==null) {
            return false;
        }
        if(p == null && q == null) {
            //這個有兩種意思 第一層代表的是兩個爲空的樹相同;
            //還又一種是p和q已經從root節點發生移動並且這樣兩個一直保持在value相等
            //p爲空時q爲空則是相等的兩個樹
            return true;
        }
        if(p.val != q.val) {
            return false;
        }
        //此時情況爲根已經相等,以根-》左-》右進行判斷
        return 
        isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章