首页 > 代码库 > 树的基本操作
树的基本操作
判断两棵树是否相同
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; } }
树的基本操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。