zoukankan      html  css  js  c++  java
  • [LeetCode#101]Symmetric Tree

    The problem:

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3
    

    But the following is not:

        1
       / 
      2   2
          
       3    3
    

    Note:
    Bonus points if you could solve it both recursively and iteratively.

    My analysis:

    The problem is little tricky, but it provoides an very important skill in sovling symmetric problem.
    Key: the binary tree is the best instance to explore sysmmetric properity.
    Let's think in this way.
    The tree A has its mirror B. If A is a sysmmetric tree <==> A and B should be the same.
    Apparently, any move on B(left search or right search), it's equal to the oppsite move on A.(B is the mirror image).
    Thus we could use a A to emmulate any move on B(just opposite the move).

    return helper(cur_root1.left, cur_root2.right) && helper(cur_root1.right, cur_root2.left);

    Then, we could use the classic method of testing if two trees are matching, to test on tree A and B(imitate on A).

    public class Solution {
        public boolean isSymmetric(TreeNode root) {
            if (root == null)
                return true;
        
            return helper(root, root);
        }
        
        private boolean helper(TreeNode cur_root1, TreeNode cur_root2) {
            
            if (cur_root1 == null && cur_root2 == null)
                return true;
            
            if (cur_root1 == null || cur_root2 == null)
                return false;
            
            if (cur_root1.val != cur_root2.val)
                return false;
            
            return helper(cur_root1.left, cur_root2.right) && helper(cur_root1.right, cur_root2.left);
        }
    }
  • 相关阅读:
    WPF Timer替代者
    <转>Change the Background of a selected ListBox Item
    WPF Button样式模板
    WPF中自定义只能输入数字的TextBox
    ansible playbook模式及语法
    数据挖掘Kaggle
    电影网站
    数据挖掘面临的科学和工程的新问题
    KDD Cup 2012(今年数据挖掘在中国)
    能力是在执行中实现的,要高节奏不要详细的设计
  • 原文地址:https://www.cnblogs.com/airwindow/p/4216056.html
Copyright © 2011-2022 走看看