提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
二叉树的递归分为「遍历」和「分解问题」两种思维模式,这道题需要用到「分解问题」的思维。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<Integer,Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
for(int i = 0; i < inorder.length; i ++){
map.put(inorder[i],i);
}
return fun(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
}
public TreeNode fun(int[] inorder, int[] postorder, int inLow, int inHigh,int postLow,int postHigh){
if(inLow > inHigh){
return null;
}
int index = map.get(postorder[postHigh]);
TreeNode cur = new TreeNode(postorder[postHigh]);
int len = index - inLow;
cur.left = fun(inorder,postorder,inLow,index-1,postLow,postLow+len-1);
cur.right = fun(inorder,postorder,index+1,inHigh,postLow+len,postHigh-1);
return cur;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<Integer,Integer> map = new HashMap<>();
public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
for(int i = 0; i < postorder.length; i ++){
map.put(postorder[i],i);
}
return fun(preorder,postorder,0,preorder.length-1,0,postorder.length-1);
}
public TreeNode fun(int[] preorder,int[] postorder,int preLow, int preHigh,int postLow,int postHigh){
if(preLow > preHigh){
return null;
}
TreeNode cur = new TreeNode(preorder[preLow]);
if(preLow + 1 <= preHigh){
int index = map.get(preorder[preLow+1]);
int len = index - postLow +1;
cur.left = fun(preorder,postorder,preLow+1,preLow+len,postLow,index);
cur.right = fun(preorder,postorder,preLow+len+1,preHigh,index+1,postHigh-1);
}
return cur;
}
}
class Solution {
public boolean isValidSerialization(String preorder) {
int edge = 1;
for(String s : preorder.split(",")){
if(s.equals("#")){
edge -= 1;
if(edge < 0){
return false;
}
}else{
edge -= 1;
if(edge < 0){
return false;
}
edge += 2;
}
}
return edge == 0;
}
}
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val,Node _left,Node _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
Node pre = null, first = null;
boolean flag = true;
public Node treeToDoublyList(Node root) {
if(root == null){
return null;
}
fun(root);
first.left = pre;
pre.right = first;
return first;
}
public void fun(Node root){
if(root == null){
return ;
}
fun(root.left);
if(pre != null){
pre.right = root;
root.left = pre;
}
pre = root;
if(flag){
first = root;
flag = false;
}
fun(root.right);
}
}