Leetcode - Count Univalue Subtrees

My code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int counter = 0;
    public int countUnivalSubtrees(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        helper(root);
        return counter;
    }
    
    private int helper(TreeNode root) {
        if (root.left == null && root.right == null) {
            counter++;
            return root.val;
        }
        else if (root.left == null) {
            int ret = helper(root.right);
            if (ret == -1) {
                return -1;
            }
            else if (ret != root.val) {
                return -1;
            }
            else {
                counter++;
                return ret;
            }
        }
        else if (root.right == null) {
            int ret = helper(root.left);
            if (ret == -1) {
                return -1;
            }
            else if (ret != root.val) {
                return -1;
            }
            else {
                counter++;
                return ret;
            }
        }
        else {
            int ret1 = helper(root.left);
            int ret2 = helper(root.right);
            if (ret1 == -1 || ret2 == -1) {
                return -1;
            }
            else {
                if (ret1 == root.val && ret2 == root.val) {
                    counter++;
                    return ret1;
                }
                else {
                    return -1;
                }
            }
        }
    }
}

post-order recursion

看了下答案,和我差不多的思路,但寫的更加簡潔,可能有些情況不用再細(xì)分了。

Anyway, Good luck, Richardo! -- 09/06/2016

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • My code: My test result: 這道題目最簡單的做法,就是直接隨便遍歷。但肯定是不對的,太慢了。...
    Richardo92閱讀 1,059評論 0 1
  • My code: My test result: 這道題目還是比較簡單的,但是還是過了好幾次才pass。這是不好的...
    Richardo92閱讀 415評論 0 1
  • 10月24日,我大隊劉蘭中隊聯(lián)合縣局設(shè)卡人員,在柏林子執(zhí)法服務(wù)點對過往車輛進行嚴(yán)格查控,嚴(yán)查各類交通違法行為,確保...
    孔得銳閱讀 251評論 0 0
  • 你以為宮寒只是子宮寒冷?錯了!宮寒=孩子不來+子宮肌瘤+卵巢衰退! 2017-09-15 艾眾生 你以為宮寒只是子...
    巴青扎巴閱讀 626評論 2 2
  • 獨行小區(qū)間 陽光暖 樹蔭濃 藍天擁抱著白云 綠草映襯著小花 心中歌兒蕩漾 赴一個約會 水庫橫臥在山腳 綠樹掩映著...
    創(chuàng)造全新幸福生活閱讀 273評論 0 1