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;    
        }
    }
  • 相关阅读:
    Ubuntu安装qBittorrent
    资深程序猿冒死揭开软件潜规则:无法维护的代码
    Oracle11g Active Data Guard搭建、管理
    Android 扁平化button
    Eclipse Android 代码自己主动提示功能
    Echoprint系列--编译
    一步步玩pcDuino3--mmc下的bootloader
    【Discuz】去除版权信息,标题栏与底部改动
    phoenixframe自己主动化測试平台对div弹出框(如弹出的div登陆框)的处理
    UVa
  • 原文地址:https://www.cnblogs.com/team42/p/7010991.html
Copyright © 2011-2022 走看看