zoukankan      html  css  js  c++  java
  • LeetCode Same Tree

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSameTree(TreeNode *p, TreeNode *q) {
            int v = ((p == NULL) << 1) + (q == NULL);
            if (v == 0x2 || v == 0x1) return false; // one NULL the other not NULL
            if (v == 0x3) return true;              // both NULL
            if (p->val != q->val) return false;     // value not match
            return isSameTree(p->left, q->left)     // check subtree
                        && isSameTree(p->right, q->right);
        }
    };

    继续水

    第二轮:

    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代码:

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public boolean isSameTree(TreeNode p, TreeNode q) {
    12         return dfs(p, q);
    13     }
    14     
    15     public boolean dfs(TreeNode root, TreeNode pair) {
    16         if (root == null && pair == null) {
    17             return true;
    18         }
    19         if (root == null || pair == null) {
    20             return false;
    21         }
    22         if (root.val != pair.val) {
    23             return false;
    24         }
    25         return dfs(root.left, pair.left)
    26                 && dfs(root.right, pair.right);
    27     }
    28 }
  • 相关阅读:
    时间记录日志
    软件工程作业02
    个人学习进度(第二周)
    《大道至简》第二章读后感
    《大道至简》第一章读后感
    构建之法阅读笔记02
    构建之法阅读笔记01
    web开发
    Tomcat的安装与环境配置
    java-10异常处理动手动脑
  • 原文地址:https://www.cnblogs.com/lailailai/p/3806014.html
Copyright © 2011-2022 走看看