zoukankan      html  css  js  c++  java
  • 树的基本操作

    判断两棵树是否相同

    public class Solution {
        /**
         * @param a, b, the root of binary trees.
         * @return true if they are identical, or false.
         */
        public boolean isIdentical(TreeNode a, TreeNode b) {
             if(a==null&&b==null){
                return true;
            }
            else if(a==null||b==null){
                return false;
            }
            if(a.val != b.val) return false;
            
            return isIdentical(a.left,b.left)&&isIdentical(a.right,b.right);
        }
    }

    翻转二叉树

    public class Solution {
        /**
         * @param root: a TreeNode, the root of the binary tree
         * @return: nothing
         */
        public void invertBinaryTree(TreeNode root) {
            if (root == null) return ;
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            invertBinaryTree(root.right);
            invertBinaryTree(root.left);
            
        }
    }

    克隆二叉树

    public class Solution {
        /**
         * @param root: The root of binary tree
         * @return root of new tree
         */
         
        public TreeNode cloneTree(TreeNode root) {
           if(root == null) return null;
           TreeNode res = new TreeNode(root.val);
           res.left = cloneTree(root.left);
           res.right = cloneTree(root.right);
           return res;
        }
    }

    求最小深度

    public class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: An integer.
         */
         
        public int minDepth(TreeNode root) {
             if (root == null) return 0;
            if (root.left == null && root.right == null) return 1;
            if(root.left == null) return minDepth(root.right)+1;
            if(root.right == null) return minDepth(root.left)+1;
            return Math.min(minDepth(root.left),minDepth(root.right))+1;
        }
       
    }

     二叉树的最大节点

    public class Solution {
        /**
         * @param root the root of binary tree
         * @return the max ndoe
         */
         TreeNode res = new TreeNode(Integer.MIN_VALUE);
        public TreeNode maxNode(TreeNode root) {
            if(root == null) return null;
            else if(root.val > res.val) res = root;
            maxNode(root.left);
            maxNode(root.right);
            return res;    
        }
    }
  • 相关阅读:
    C#多线程之基础篇3
    C#多线程之基础篇2
    C#多线程之基础篇1
    Log4net入门(帮助类篇)
    Log4net入门(WCF篇)
    Log4net入门(ASP.NET MVC 5篇)
    Log4net入门(SQL篇)
    深入理解java:4.3. 框架编程之MyBatis原理深入解析
    深入理解java:4.2. 框架编程之Spring框架的设计理念
    深入理解java:4.1. 框架编程之Spring MVC
  • 原文地址:https://www.cnblogs.com/team42/p/7010991.html
Copyright © 2011-2022 走看看