zoukankan      html  css  js  c++  java
  • 100. Same Tree(二叉树、递归)

    Given two binary trees, write a function to check if they are the same or not.

    Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

    给出两个二叉树,写一个算法来检查它们是否相同。若两棵树结构完全相同,且每个节点有相同值,则为两棵树相同。

    Example 1:

    Input:     1         1
              /        / 
             2   3     2   3
    
            [1,2,3],   [1,2,3]
    
    Output: true
    

    Example 2:

    Input:     1         1
              /           
             2             2
    
            [1,2],     [1,null,2]
    
    Output: false
    

    Example 3:

    Input:     1         1
              /        / 
             2   1     1   2
    
            [1,2,1],   [1,1,2]
    
    Output: false

    大神答案micheal.zhou

    递归方式,简单明了~
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null) return false;
        if(p.val == q.val)
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        return false;
    }
     

     我自己的答案(非递归),这个题其实主要考察二叉树的遍历,下面链接里非常详细地总结了二叉树前、中、后序遍历的递归和非递归方法,可读性比较高。

    http://blog.csdn.net/apandi_/article/details/52916523

    /**
    * Definition for a binary tree node.
    * public class TreeNode {
    * int val;
    * TreeNode left;
    * TreeNode right;
    * TreeNode(int x) { val = x; }
    * }
    */
    import java.util.Stack;

    class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
    Stack<TreeNode> st_p = new Stack<TreeNode>();
    Stack<TreeNode> st_q = new Stack<TreeNode>();

    while (p != null || !st_p.empty()) {
    while (p != null) {
    if (q == null)
    return false;

    if (p.val != q.val)
    return false;

    st_p.push(p);
    st_q.push(q);
    p = p.left;
    q = q.left;
    }

    if (!st_p.empty()) {
    if(st_q.empty()||q!=null)
    return false;
    p=st_p.pop();
    q=st_q.pop();
    p=p.right;
    q=q.right;
    }
    }

    if (q!=null||!st_q.empty())
    return false;

    return true;
    }
    }

  • 相关阅读:
    Demo学习: DownloadDemo
    Demo学习: FileUpload
    Demo学习: Dialogs Anonymous Callback
    Demo学习: Cookies Demo
    Demo学习: CustomException
    Demo学习: Collapsible Panels
    Demo学习: ColumnSort
    Demo学习: ClientInfo
    Demo学习: Closable Tabs
    Demo学习: ClientEvents
  • 原文地址:https://www.cnblogs.com/mafang/p/8480409.html
Copyright © 2011-2022 走看看