题解 | #牛群的树形结构展开II#
牛群的树形结构展开II
https://www.nowcoder.com/practice/3e89ca58f76d4e6aa44cf29569017410
题目考察的知识点是:
本题主要考察二叉树的遍历。
题目解答方法的文字分析:
构建虚拟头节点和指向当前节点的指针cur,中序遍历二叉树,创建节点temp,在将cur.right指向temp,递归中序遍历即可。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return TreeNode类 */ public TreeNode flattenII (TreeNode root) { // write code here if (root == null) { return null; } ArrayList<Integer> arrayList = new ArrayList<>(); flatten(root, arrayList); TreeNode head = new TreeNode(arrayList.get(0)); TreeNode temp = head; for (int i = 1; i < arrayList.size(); i++) { TreeNode treeNode = new TreeNode(arrayList.get(i)); temp.right = treeNode; temp = temp.right; } return head; } public void flatten (TreeNode root, ArrayList<Integer> arrayList) { if (root != null) { flatten(root.left, arrayList); arrayList.add(root.val); flatten(root.right, arrayList); } } }#题解#