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;    
        }
    }
  • 相关阅读:
    nodejs学习笔记
    php操作mysql数据库
    HTML5 新特性总结
    万恶的浏览器兼容问题
    图标字体使用方法
    托管代码
    进程间通信,把字符串指针作为参数通过SendMessage传递给另一个进程,不起作用
    利用自定义消息处理函数的WPARAM或LPARAM参数传递指针
    自定义消息中如果需要定义WPARAM和LPARAM,该怎么使用和分配?
    提高VS2010运行速度的技巧+关闭拼写检查
  • 原文地址:https://www.cnblogs.com/team42/p/7010991.html
Copyright © 2011-2022 走看看