zoukankan      html  css  js  c++  java
  • [LeetCode#100]Same Tree

    The problem:

    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.

    My analysis:

    This problem is very easy, and we can conclude some common routines in writing a recursion program.
    1. Usually, we need future information(information from post recursion level) to make decision
    return helper(cur_root1.left, cur_root2.left) && helper(cur_root1.right, cur_root2.right);
    Thus, until we reach the base case, we won't return "true" value.

    if (cur_root1 == null && cur_root2 == null) //also take care of the illegal base case!!!
        return true;

    2. During the recursion level that is not he base level, we won't return "true" value based on current level's judgement. But we can return "false" value to indicate the violation happens in the current level, we no longer need to go on the searching!
    Note:this idea is very classic in constraining the searching space.

    if (cur_root1.val != cur_root2.val) 
        return false;

    My solution:

    public class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            
            return helper(p, q);
        }
        
        private boolean helper(TreeNode cur_root1, TreeNode cur_root2) {
            
            if (cur_root1 == null && cur_root2 == null) //both two roots are null, only base case or violation can directly return
                return true;
            
            if (cur_root1 == null || cur_root2 == null) //only one root is null
                return false; 
            
            if (cur_root1.val != cur_root2.val) 
                return false; 
                
            return  helper(cur_root1.left, cur_root2.left) && helper(cur_root1.right, cur_root2.right);
        }
    }
  • 相关阅读:
    写作的益处
    【转载】德鲁克:激发我一生的七段经历
    PS如何删除灰色的自动切片
    其他经验博文分类链接
    LODOP单个简短问答(小页面无需拖动滚动条)
    LODOP导出excel的页眉页脚
    LODOP导出和写入excel测试
    LODOP导出Excel简短问答和相关博文
    Lodop导出excel带数字格式
    LODOP批量打印判断是否加入队列1
  • 原文地址:https://www.cnblogs.com/airwindow/p/4216036.html
Copyright © 2011-2022 走看看