标签:克隆 判断 操作 return bin class 二叉树 oid sid
判断两棵树是否相同
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; } }
标签:克隆 判断 操作 return bin class 二叉树 oid sid
原文地址:http://www.cnblogs.com/team42/p/7010991.html