题解 | #牛群的树形结构展开II#
牛群的树形结构展开II
https://www.nowcoder.com/practice/3e89ca58f76d4e6aa44cf29569017410
知识点
树,中序遍历
解题思路
新建一个节点curr,中序遍历树,
如果有左子树就先走左子树,左子树走完了将当前的节点值赋值给curr的右子树上,左子树赋空,再移动到curr的右子树上等待下次操作。
再将root的右子树进行同样操作,最后返回指向curr根节点的ans。
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类 */ TreeNode ans; TreeNode curr; public TreeNode flattenII (TreeNode root) { // write code here if(root == null) return null; ans = new TreeNode(0); curr = ans; fun(root); return ans.right; } public void fun(TreeNode root){ if(root.left != null){ fun(root.left); } curr.left = null; curr.right = new TreeNode(root.val); curr = curr.right; if(root.right != null){ fun(root.right); } } }