1、基本思想
1.1、递归遍历
模板:
:::tips
1、确定函数的返回值
2、确定终止条件
3、确定单层递归的逻辑
:::
1.2、迭代法实现遍历
基本思想:使用栈来模拟递归
1.2.1、前序遍历
手动模拟 :::tips 利用栈先进后出的特性,右左中节点以此入栈 :::
代码 ```java class Solution { public List
preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>();if (root == null){return result;}Stack<TreeNode> stack = new Stack<>();stack.push(root); //根节点入栈while (!stack.isEmpty()){TreeNode node = stack.pop(); //出栈result.add(node.val);if (node.right != null){stack.push(node.right);//右节点入栈}if (node.left != null){stack.push(node.left); //左节点入栈}}return result; //返回节点
} }
<a name="Ik60o"></a>### 1.2.2、后序遍历- 思想:::tips基本思想与前序一致,调整左右节点的入栈顺序,最后在反转数组<br />中左右-->中右左-->左右中:::- 代码```javaclass Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null){return result;}Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()){TreeNode node = stack.pop();result.add(node.val);if (node.left != null){ //左节点stack.push(node.left);}if (node.right != null){ //右节点stack.push(node.right);}}Collections.reverse(result); //数组反转return result;}}
1.2.3、中序遍历
思想 :::tips 根节点入栈,如果左子树不为空,则持续将左子树加入栈中
左子树为空时,将节点出栈,并记录到结果数组中,然后访问右节点 :::代码
public List<Integer> inorderTraversal(TreeNode root) {ArrayList<Integer> integers = new ArrayList<>();if (root==null) return integers;Stack<TreeNode> stack = new Stack<>();TreeNode node = root; //与其他两种方式不同,这里无需进行初始化while (node!=null || !stack.isEmpty()){if (node!=null){stack.push(node);node=node.left;}else {node= stack.pop();//无左子树,出栈,并加入结果中integers.add(node.val);node=node.right; //}}return integers;}
1.3、层次遍历
思想 :::tips 利用队列先进先出的特点
从根节点开始入队,获取当前队列大小,每次只访问当前层的节点,将当前节点加入对应结果的数组中,然后将子节点入队,供下一层重复当前操作,直至队列为空时返回结果。 :::代码
public List<List<Integer>> levelOrder(TreeNode root) {ArrayList<List<Integer>> lists = new ArrayList<>();if (root==null) return lists;Queue<TreeNode> queue = new LinkedList<TreeNode>(); //LinkList实现的一个队列queue.offer(root);while (!queue.isEmpty()){ArrayList<Integer> level = new ArrayList<Integer>(); //当前层的结果int size= queue.size(); //从根节点开始,利用队列先进先出的特点,每次访问当前层的节点,并将其对应子节点加入到队列中供下次访问。System.out.println("队列大小"+size);for (int i = 0; i < size; i++) {TreeNode node = queue.poll();level.add(node.val);if (node.left!=null) queue.add(node.left);if (node.right!=null) queue.add(node.right);}lists.add(level);}return lists;}
1.4、反转二叉树
思路简单,只需要在递归、迭代和层次的基础上加上swap就行
DFS
public TreeNode invertTree(TreeNode root) {TreeNode head = root;if (root==null) return root;swap(root);invertTree(root.left);invertTree(root.right);return root;}
BFS
public TreeNode invertTreeBFS(TreeNode root){TreeNode head = root;if (head==null) return root;Queue<TreeNode> queue =new LinkedList<>();queue.offer(root);while (!queue.isEmpty()){int size = queue.size();for (int i = 0; i < size; i++) {TreeNode node =queue.poll();swap(node);if (node.left!=null) queue.offer(node.left);if (node.right!=null) queue.offer(node.right);}}return head;}
迭代
public TreeNode inver(TreeNode root){TreeNode head = root;if (root==null) return root;Stack<TreeNode> treeNodes = new Stack<>();treeNodes.push(root);while (!treeNodes.isEmpty()){TreeNode node = treeNodes.pop();swap(node);if (node.left!=null) treeNodes.push(node.left);if (node.right!=null) treeNodes.push(node.right);}return head;}
1.4、对称二叉树
二叉树是否对称,需要将左右的外侧与外侧比,内侧与内侧比
- 递归
递归函数是布尔值,终止条件是如果左右子树不相等则返回false,左子树右子树都为空时返回true,左右子树相等时,用外侧与内侧同时递归,在内外都为true时,才返回true,并返回上一层递归,以此类推。
public boolean isSymmetric(TreeNode root) {if (root==null) return false;return conpare(root.left,root.right);}boolean conpare(TreeNode left,TreeNode right){//当左右节点不同时为空时,返回fif (left==null&&right!=null || left!=null&&right==null) return false;//当左右节点都为空时,返回telse if (left==null&&right==null) return true;//返回条件//当不为空,且左右节点不一致else if (left.val!=right.val) return false;//剩下一种可能,当左右节点不为空且值不一致时else {boolean out = conpare(left.left,right.right); //子树的外侧boolean inner = conpare(left.right,right.left); //子树的内测return out&&inner; //只有内外全部一致的时候才能返回true}
- 迭代
迭代思路简单,可以使用队列或者栈作为工具进行判断,此处以队列为例 主要思路还是左右的内侧与外侧同时入队,来比较左右的大小
public boolean isSymmetric(TreeNode root) {if (root==null) return false;Queue<TreeNode> queue = new LinkedList<>();//将根节点的左右子树入队queue.offer(root.left);queue.offer(root.right);while (!queue.isEmpty()){//两个数据出队TreeNode left = queue.poll();TreeNode right = queue.poll();if (left==null&&right==null) continue;else if (right==null || left==null || right.val!=left.val) return false;//外侧入队queue.offer(left.left);queue.offer(right.right);//内侧入队queue.offer(left.right);queue.offer(right.left);}return true;}
迭代只是一种思想,且并非只有栈一种处理方式
1.5、二叉树的最大深度
前序求的就是深度,使用后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)
而根节点的高度就是二叉树的最大深度,所以本题中我们通过后序求的根节点高度来求的二叉树最大深度。
1.5.1、递归法
后序遍历
public int maxDepth(TreeNode root) {//从底部开始算,因此本质上是求其深度,深度和高度相等if (root==null) return 0; //叶子节点高度为1return Math.max(maxDepth(root.left),maxDepth(root.right))+1; //简略的后序遍历}
前序遍历
int result;public int maxDepth(TreeNode root) {result=0;if(root==null) return 0;getDeepth (root,1); //根节点深度为1return result;}void getDeepth (TreeNode node,int deepth){result = Math.max(result,deepth); //前序遍历// System.out.println(String.valueOf(node.val)+"对应深度:"+deepth);if(node.left==null&&node.right==null) return; //递归必有返回条件if (node.left!=null){ //左getDeepth(node.left,++deepth);deepth--;}if (node.right!=null){getDeepth(node.right,++deepth);deepth--;}return;}
1.5.2、迭代
使用层次遍历,每层deepth + 1,代码省略
1.6、二叉树的最小深度
求深度问题,默认使用后序排序 由于最小深度是对于头节点到叶子节点的距离,所以需要排除左右节点为空的情况
public int minDepth(TreeNode root) {if (root==null) return 0;int lefth=minDepth(root.left);int righth=minDepth(root.right);//题目是根节点到叶子节点的最小距离//所以需要排除掉左右子树分别为空的情况if (root.left!=null&&root.right==null) return 1+lefth;if (root.right!=null&&root.left==null) return 1+righth;return 1+Math.min(lefth,righth);}
1.6、二叉树的所有路径
求路径需要用后续遍历 此题可分为两种情况:
- 一般二叉树的求解
- 完全二叉树的求解
- 一般二叉树:
```java
// 通用递归解法
public int countNodes(TreeNode root) {
}if(root == null) {return 0;}return countNodes(root.left) + countNodes(root.right) + 1;
2. 完全二叉树```javapublic int countNodes(TreeNode root) {if(root==null) return 0; //出递归条件//取出左右节点TreeNode left = root.left;TreeNode right = root.right;//定义左右节点的长度int leftl=0,rightl=0;//遍历左节点while (left!=null){left=left.left;leftl++;}while (right!=null){right=right.right;rightl++;}//如果左右节点长度一致,则说明该子树为满二叉树,用满二叉树的计算公式if (rightl==leftl) return (2<<leftl)-1;//如果左右节点不一致,则递归访问左右节点长度,然后加1 (子树根节点)return countNodes(root.left)+countNodes(root.right)+1;}
补充:
1.7、左叶子之和
由于是左叶子,因此不能简单的用层次遍历取最左边的节点 可以使用DFS 前序遍历 本题使用迭代的方式
public int sumOfLeftLeaves(TreeNode root) {if(root==null) return 0;Stack<TreeNode> stack = new Stack<>();stack.push(root);int res =0 ;//用栈使用迭代遍历进行前序遍历while (!stack.isEmpty()){TreeNode node = stack.pop();//左叶子树的遍历条件if (node.left!=null&&node.left.left==null&&node.left.right==null){res+=node.left.val;}if (node.left!=null) stack.push(node.left);if (node.right!=null) stack.push(node.right);}return res;}
1.8、路径之和
public boolean hasPathSum(TreeNode root, int targetSum) {if (root==null) return false;return getSum(root,targetSum);}//定义的递归函数,返回值是Booleanboolean getSum(TreeNode node,int tar){// System.out.println("当前节点:"+ node.val+"当前tar: "+tar);//如果叶节点,且路径之和和目标值相等,则返回trueif (node.left==null && node.right==null && tar==node.val) return true;if (node.left==null &&node.right==null) return false;if (node.left!=null){//子树正确,也直接返回if(getSum(node.left,tar-node.val)) return true;}if (node.right!=null){//子树正确,也直接返回if (getSum(node.right,tar-node.val)) return true;}//如果不符合上面的条件,则返回freturn false;}
1.9、中序遍历与后续遍历序列构造二叉树
树的还原过程:
- 首先在后序遍历序列中找到根节点(最后一个元素)
- 根据根节点在中序遍历序列中找到根节点的位置
- 根据根节点的位置将中序遍历序列分为左子树和右子树
- 根据根节点的位置确定左子树和右子树在中序数组和后续数组中的左右边界位置
- 递归构造左子树和右子树
- 返回根节点结束
用到的变量:
- HashMap memo 需要一个哈希表来保存中序遍历序列中,元素和索引的位置关系.因为从后序序列中拿到根节点后,要在中序序列中查找对应的位置,从而将数组分为左子树和右子树
- int ri 根节点在中序遍历数组中的索引位置
- 中序遍历数组的两个位置标记 [is, ie],is 是起始位置,ie 是结束位置
- 后序遍历数组的两个位置标记 [ps, pe] ps 是起始位置,pe 是结束位置
位置关系的计算
左子树-中序数组 is = is, ie = ri - 1 左子树-后序数组 ps = ps, pe = ps + ri - is - 1 (pe计算过程解释,后续数组的起始位置加上左子树长度-1 就是后后序数组结束位置了,左子树的长度 = 根节点索引-左子树) 右子树-中序数组 is = ri + 1, ie = ie 右子树-后序数组 ps = ps + ri - is, pe - 1
class Solution {//map辅助空间,存储中序值-位置的映射HashMap<Integer, Integer> map = new HashMap<>();//记录后序遍历数组int[] post;public TreeNode buildTree(int[] inorder, int[] postorder) {for (int i = 0; i < inorder.length; i++) {map.put(inorder[i], i);}//存入后序辅助数组post=postorder;return buildTree(0, inorder.length - 1, 0, postorder.length - 1);}//is:前序始节点,ie:前序终结点,ps:后序始节点,pe:后序终结点TreeNode buildTree(int is,int ie,int ps,int pe) {//递归函数的终止条件if (is>ie || ps>pe) return null;//由后序遍历性质,得到子树的头节点int root = post[pe];//在中序的头节点位置,由ri将树分为左右子树int ri = map.get(root);TreeNode node = new TreeNode(root);//左右指针分别指向左右子树node.left = buildTree(is, ri - 1, ps, ps+ ri-is - 1);node.right = buildTree(ri + 1, ie, ps + ri - is, pe - 1);//返回根节点return node;}}
1.10、从前序与中序遍历序列构造二叉树
1.11、最大二叉树
生成二叉树都是相同的思路,通过递归遍历数组,生成子树,需要确认端点值 与上面的解决方式不同,此题直接使用下标进行记录,不需要使用辅助map和数组
public TreeNode constructMaximumBinaryTree(int[] nums) {return buildTrees(nums,0, nums.length - 1);}TreeNode buildTrees(int[] arr,int low, int high) {if (low>high) return null;int max = low;for (int i = low; i <= high; i++) {if (arr[max]<arr[i]) max = i;}TreeNode node = new TreeNode(arr[max]);node.left = buildTrees(arr,low, max-1);node.right = buildTrees(arr,max+1, high);return node;}
辅助版(速度很慢)
class Solution {HashMap<Integer, Integer> maps = new HashMap<>();int[] num;public TreeNode constructMaximumBinaryTree(int[] nums) {if (nums.length==0) return null;for (int i = 0; i < nums.length; i++) {maps.put(nums[i], i);}num = nums;return buildTrees(0, nums.length - 1);}TreeNode buildTrees(int low, int high) {if (low>high) return null;int max = getMax(num, low, high);System.out.println(max);int ri = maps.get(max);TreeNode node = new TreeNode(max);node.left = buildTrees(low, ri - 1);node.right = buildTrees(ri + 1, high);return node;}int getMax(int[] arr, int low, int high) {System.out.println("low:"+low + " high:"+high);int max = 0;for (int i = low; i <= high; i++) {if (max<arr[i]) max = arr[i];}return max;}}
1.12、验证搜索二叉树
思路模拟:如果是一个正确的搜索二叉树,然后按照 中序遍历 这个二叉树生成一个数组,那么数组必是有序的
- 方法1:定义一个无限小的值,中序遍历,if(root.val>min) min=root.val else return false;
- 方法2:双指针,定义前后指针来比较前后的值。
因此我们可以确定,此题中我们需要使用中序遍历这个二叉树
递归
TreeNode pre;public boolean isValidBST(TreeNode root) {if (root == null) return true;//左boolean left = isValidBST(root.left);if (!left) return false;//中//如果上一节点不为空,当前节点与上一节点比较if (pre!=null && root.val <= pre.val) return false;//双针织,暂存当前节点,在与下一层的值比较大小pre = root;//右boolean rigtht = isValidBST(root.right);//直接返回rightreturn rigtht;}
1.13、二叉搜索树中的众数
用一个全局变量记录最大次数,如果当前数字的出现次数更大,则结果更新,如果相同,则插入,否则不变
ArrayList<Integer> resList = new ArrayList<>();TreeNode pre;int max;HashMap<Integer, Integer> map = new HashMap<>();public int[] findMode(TreeNode root) {if (root==null) return null;max = 1;track(root);int[] res = new int[resList.size()];for (int i = 0; i < resList.size(); i++) {res[i] = resList.get(i);}return res;}void track(TreeNode node) {if (node == null) {return;}track(node.left);map.put(node.val, map.getOrDefault(node.val, 0) + 1);if (max<map.get(node.val)){System.out.println(map.toString());System.out.println(max);resList.clear();resList.add(node.val);max = map.get(node.val);} else if (max == map.get(node.val)) {resList.add(node.val);}pre= node;track(node.right);}
1.14、二叉树的最近公共祖先
本题是求最近的公共祖先,因此需要二叉树由下而上的遍历 因此需要用到后序遍历 先设想一个最理想的情况: root的左右节点分别为 p , q 此时我们利用后序遍历,如果子树中有p,q 那么直接返回 那么此时root 的左右节点不为空,root就是 p,q的最近公共祖先。 另外一种情况,当root = p 时, 按照以上逻辑直接返回p , 此时p就是p、q的最近祖先。
//递归的访问子树,并且每次返回一个节点,供上层递归判断public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {//递归返回条件,可以整合if (root==null) return root;if (p == root || q == root) {return root;}//后序遍历,递归的访问左右节点,并用left,right 记录节点返回值TreeNode left = lowestCommonAncestor(root.left, p,q);TreeNode right = lowestCommonAncestor(root.right, p, q);//left right都不为空,那么root就是最近公共节点if (left != null && right != null) {return root;} else //left为空,right不为空 返回rightif (left == null && right != null) {return right;} else //left不为空,right为空,返回leftif (left != null && right == null) {return left;} else return null;}
1.15、二叉树的插入
- 由于本题不限制插入形式,因此第一种方式使用最简单的直接插入
中序遍历+双指针
TreeNode pre;public TreeNode insertIntoBST(TreeNode root, int val) {//root为空的特例if (root == null && pre == null) {return new TreeNode(val);}if (root == null && pre!=null) {TreeNode node = new TreeNode(val);if (val < pre.val) {pre.left = node;}else {pre.right = node;}return pre;}if (val < root.val) {pre = root;insertIntoBST(root.left, val);}if (val > root.val) {pre = root;insertIntoBST(root.right, val);}return root;}
直接递归
class Solution {public TreeNode insertIntoBST(TreeNode root, int val) {if (root == null) // 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。return new TreeNode(val);if (root.val < val){root.right = insertIntoBST(root.right, val); // 递归创建右子树}else if (root.val > val){root.left = insertIntoBST(root.left, val); // 递归创建左子树}return root;}}
迭代
public TreeNode insertIntoBST(TreeNode root, int val) {TreeNode node =new TreeNode(val);if (root==null) return node;TreeNode cur = root;TreeNode pre = root;while (cur != null) {pre = cur;if (val<cur.val) cur = cur.left;else if (val>cur.val) cur = cur.right;}if (pre.val>val) pre.left = node;else pre.right = node;return root;}
1.16、二叉树的删除
在二叉树的删除中,主要分为四种情况
- 叶子:左右子树都为空
- 左子树为空,右子树不为空
- 右子树为空,左子树不为空
- 左右子树都不为空
public TreeNode deleteNode(TreeNode root, int key) {if (root.val == key) {if (root.left == null && root.right == null) {return null;}if (root.left == null && root.right != null) {return root.right;}if (root.left != null && root.right == null) {return root.left;}if (root.left != null && root.right != null) {TreeNode cur = root.right;//遍历至左目标树while (cur.left != null) {cur = cur.left;}System.out.println(root.val);System.out.println(cur.val);//最左的叶节点的左子树指向目标节点的左子树cur.left = root.left;//此时情况可视为左子树为空,右子树不为空,返回右子树return root.right;}}if (root != null && key < root.val) {//左子树链接root.left = deleteNode(root.left, key);}if (root != null && key > root.val) {//右子树链接root.right = deleteNode(root.right, key);}return root;}
1.17、修剪二叉搜索树
- 返回条件:为 null 时,返回null
- 如果当前节点值小于low,开始递归访问又节点
- 如果大于high,则递归访问左节点
- 连接当前节点的左右子树
- 返回根节点
public TreeNode trimBST(TreeNode root, int low, int high) {if (root == null) {return null;}System.out.println("递归前:"+root.val);if (root.val < low) {return trimBST(root.right, low, high);}if (root.val > high) {return trimBST(root.left, low, high);}//对当前节点进行链接root.left = trimBST(root.left, low, high);root.right = trimBST(root.right, low, high);System.out.println("递归后:"+root.val);return root;}
1.18、完全二叉树的节点数量
在层次递归中,每层都需要遍历两端的节点,得到左右子树的深度 如果符合左右相等的条件,则符合满二叉树的条件,代入公式,然后返回结果; 如果不同则继续遍历当前层的根节点的左右子树 返回左右子树之和节点之和+1 (包含当前节点)
public int countNodes(TreeNode root) {if (root==null) return 0;TreeNode leftNode = root.left;TreeNode rightNode = root.right;int left=0,right = 0; //只记录当前层的左右节点的深度while (leftNode != null) { //在当前层,一直往左遍历leftNode = leftNode.left;left++;}while (rightNode != null) {//在当前层,一直往右遍历rightNode = rightNode.right;right++;}if (left == right) {//根据完全二叉树性质,如果左右节点数量相等,则是满二叉树return (2 << left - 1);}//如果不满足条件,则遍历左右子树然后+1return countNodes(root.left) + countNodes(root.right)+1;}
1.19、判断平衡二叉树
此题也是求高度问题,不过需要每层需要判断左右子树的深度只差,因此需要用到后续遍历
public boolean isBalanced(TreeNode root) {return traceBalance(root) != -1;}int traceBalance(TreeNode node) {if (node == null) {return 0;}//遍历左节点int left = traceBalance(node.left);if (left==-1) return -1;//遍历右节点int right = traceBalance(node.right);if (right==-1) return -1;//如果当前节点的左右子树高度只差大于1if (Math.abs(left-right)>1) return -1;//递归从下往上返回结果,因此当前高度需要加上当前节点return Math.max(right, left) + 1;}
二、二刷
2.1、二叉树的直径
求直径,就是求树中每个节点左右子树深度之和的最大值 使用后序求得每个子树的左右节点之和,再返回递归的上一层
int res;public int diameterOfBinaryTree(TreeNode root) {res = 0;getDeept(root);return res-1;}int getDeept(TreeNode node) {if (node==null) return 0;int left = getDeept(node.left);int right = getDeept(node.right);res = Math.max(res, left + right + 1); //存取所有节点中的最大值return Math.max(left , right )+ 1; //返回最长的边}
2.2、将有序数组转化为二叉搜索树
由于数组已经有序,所以二叉搜索树的中序就是数组的遍历顺序,但是仅有中序序列没办法生成一个确定的树 由题意知左右子树只差不能大于1,因此取中间的元素作为根节点
public TreeNode sortedArrayToBST(int[] nums) {return help(0, nums.length-1, nums);}TreeNode help(int left,int right,int[] numes) {if (left > right) { //递归结束条件return null;}int mid = (left + right) / 2;// System.out.println(mid);TreeNode node = new TreeNode(numes[mid]); //创建新的节点node.left = help(left, mid - 1, numes); // 左子树连接node.right = help(mid + 1, right, numes);return node; //返回当前节点}
2.3、二叉树的右视图
本题主要思路在于求得当前层的最右元素,主要有两种方式:
BFS
通过层次遍历,获得当前层的最后一个元素
public List<Integer> rightSideView(TreeNode root) {ArrayList<Integer> res = new ArrayList<>();if (root == null) {return res;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size = queue.size();for (int i = 0; i < size; i++) {TreeNode node = queue.poll();if (i == size - 1) {res.add(node.val);}if (node.left != null) {queue.offer(node.left);}if (node.right != null) {queue.offer(node.right);}}}return res;}
DFS
以 中->右->左 的方式进行遍历,每一层获取的第一个元素即为最右侧元素 在递归中引入参数深度,获得当前递归层次的深度信息 通过res.size 与 深度的比较判断是否需要加入结果集
ArrayList<Integer> res = new ArrayList<>();public List<Integer> rightSideView(TreeNode root) {DFS(root, 0);return res;}void DFS(TreeNode node, int deep) {if (node==null) return;if (deep == res.size()) {// 如果当前节点所在深度还没有出现在res里//说明在该深度下当前节点是第一个被访问的节点//因此将当前节点加入res中res.add(node.val);}DFS(node.right, deep + 1);DFS(node.left, deep + 1);}
2.4、 二叉树展开为链表
迭代+辅助栈
public void flatten(TreeNode root) {if (root==null) return;Deque<TreeNode> stack = new LinkedList<>();TreeNode pre = null;stack.offer(root);while (!stack.isEmpty()) {TreeNode cur = stack.pop();if (pre != null) { //除去第一个节点,都执行以下操作pre.right = cur;pre.left = null;}if (cur.right != null) {stack.push(cur.right);}if (cur.left != null) {stack.push(cur.left);}pre = cur;}}
递归
TreeNode pre = null;public void flatten(TreeNode root) {postOrderTraverse(root);}public void postOrderTraverse(TreeNode root){if (root==null)return; // 递归终止条件postOrderTraverse(root.right);postOrderTraverse(root.left);root.left = null; //当前节点的左孩子指向空root.right = pre; // 右节点指向prepre = root; //pre = root ,暂存当前节点}
利用提题意求解
由于题目要求前序的性质不变,因此将当前节点的左孩子不为空时,左孩子必定在右孩子之上。 对于当前节点,如果其左子节点不为空,则在其左子树中找到最右边的节点, 作为前驱节点,将当前节点的右子节点赋给前驱节点的右子节点,然后将当前节点的左子节点赋给当前节点的右子节点,并将当前节点的左子节点设为空。 对当前节点处理结束后,继续处理链表中的下一个节点,直到所有节点都处理结束。
public void flatten(TreeNode root) {if (root == null) {return;}TreeNode cur = root;while (cur != null) {if (cur.left != null) {TreeNode next = cur.left;TreeNode pre = next;while (pre.right != null) {pre = pre.right; //找到 cur.right的前驱节点}pre.right = cur.right;cur.left = null;cur.right = next;}cur = cur.right;}}
2.5、前序中序构造二叉树
辅助map记录中序数组中值和索引的关系,辅助数组记录前序数组 采用递归遍历
HashMap<Integer, Integer> map = new HashMap<>();int[] ass;public TreeNode buildTree(int[] preorder, int[] inorder) {for (int i = 0; i < inorder.length; i++) {map.put(inorder[i], i);}ass = preorder;return buildTree(0, preorder.length - 1, 0, inorder.length - 1);}TreeNode buildTree(int preStart, int preEnd, int inStart, int inEnd) {if (preStart > preEnd || inStart > inEnd) { //递归终止条件return null;}int cur = ass[preStart];//前序数组首位即为当前需要访问的根节点// System.out.println("----> cur:"+cur);TreeNode root = new TreeNode(cur);int inPos = map.get(cur); //找到中序中的位置信息// System.out.println("----> pre:" + inPos);//位置关系可以手动推到root.left = buildTree(preStart+1, preStart+inPos-inStart, inStart, inPos-1);root.right = buildTree(preStart+inPos-inStart+1, preEnd, inPos+1, inEnd);return root;}

