不准访问
- 积分
- 102
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-5-14
- 最后登录
- 1970-1-1
|
为什么要新建一个wrapper node 类呢?用原treenode 也可以做吧?跑了一下感觉差不多
- class Solution {
- public TreeNode shuffleTreeNodes(TreeNode root) {
- List<TreeNode> list = new ArrayList<>();
- // 建一棵与原树结构完全一样的树
- TreeNode structureRoot = buildStructure(root, list);
- Collections.shuffle(list);
- // 用原结点按照结构树重构一棵树
- return shuffleTree(structureRoot, list.iterator());
- }
- private TreeNode buildStructure(TreeNode root, List<TreeNode> list) {
- if (root == null) {
- return null;
- }
-
- list.add(root);
- TreeNode structureRoot = new TreeNode(-1);
- structureRoot.left = buildStructure(root.left, list);
- structureRoot.right = buildStructure(root.right, list);
- return structureRoot;
- }
- private TreeNode shuffleTree(TreeNode structureRoot, Iterator<TreeNode> it) {
- if (structureRoot == null) {
- return null;
- }
-
- TreeNode root = it.next();
- root.left = shuffleTree(structureRoot.left, it);
- root.right = shuffleTree(structureRoot.right, it);
- return root;
- }
- }
复制代码 |
|