中序先序构造二叉树
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null || preorder.length != inorder.length || inorder.length < 1)
return null;
return construct(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode construct(int[] preorder, int ps, int pe, int[] inorder, int is, int ie){
if(ps>pe||is>ie) return null;
int curroot=preorder[ps];
int index=is;
while(index<=ie&&curroot!=inorder[index])
{
index++;
}
if(index>ie) return null;
TreeNode node=new TreeNode(curroot);
node.val=curroot;
node.left=construct(preorder,ps+1,pe-is+index,inorder,is,index-1);
node.right=construct(preorder,ps+1+index-is,pe,inorder,index+1,ie);
return node;
}
}
中序后序构造二叉树
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder==null||postorder==null||inorder.length!=postorder.length||inorder.length<1)
{
return null;
}
TreeNode root=construct(postorder,0,postorder.length-1,inorder,0,inorder.length-1);
return root;
}
public TreeNode construct(int[] postorder,int ps,int pe,int[] inorder,int is,int ie)
{
if(is>ie||ps>pe)
{
return null;
}
int curroot=postorder[pe];
int index=is;
while(index<=ie&&curroot!=inorder[index])
{
index++;
}
if(index>ie) return null;
TreeNode node=new TreeNode(curroot);
node.val=curroot;
node.left=construct(postorder,ps,pe-1-ie+index,inorder,is,index-1);
node.right=construct(postorder,pe+index-ie,pe-1,inorder,index+1,ie);
return node;
}
}
二叉树后序遍历
class Solution {
List<Integer> sum=new LinkedList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root==null) return sum;
postorderTraversal(root.left);
postorderTraversal(root.right);
sum.add(root.val);
return sum;
}
}
翻转二叉树
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null) return null;
TreeNode x=root.right;
root.right = invertTree(root.left);
root.left = invertTree(x);
return root;
}
}
二叉树的最大直径
class Solution {
int max=0;
public int diameterOfBinaryTree(TreeNode root) {
if(root==null) return 0;
cal(root);
return max;
}
public int cal(TreeNode root)
{
if (root.left == null && root.right == null) {
return 0;
}
int leftSize = root.left == null? 0: cal(root.left) + 1;
int rightSize = root.right == null? 0: cal(root.right) + 1;
max = Math.max(max, leftSize + rightSize);
return Math.max(leftSize, rightSize);
}
}
打家劫舍Ⅲ
class Solution {
public int rob(TreeNode root) {
int[] res = helper(root);
return Math.max(res[0],res[1]);
}
public int[] helper(TreeNode r){
if(r == null) return new int[2];
int[] left = helper(r.left);
int[] right = helper(r.right);
int[] res = new int[2];
res[0] = Math.max(left[0],left[1]) + Math.max(right[0],right[1]);
res[1] = r.val + left[0] + right[0];
return res;
}
}
2021-09-04
最新推荐文章于 2021-12-20 21:15:28 发布