问题描述: 给定一个二叉树,原地将它展开为链表。
例如:给定二叉树
eg: 1 / 2 5 / \ 3 4 6 将其展开为:
1 2 3 4 5 6 上代码,拿去即可运行:
package com.onlyqi.upup01.tree;
import com.onlyqi.upup01.leetcode.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
public class Test03 {
public static void main(String[] args) {
TreeNode treeNode1 = new TreeNode(1);
TreeNode treeNode2 = new TreeNode(2);
TreeNode treeNode3 = new TreeNode(3);
TreeNode treeNode4 = new TreeNode(4);
TreeNode treeNode5 = new TreeNode(5);
TreeNode treeNode6 = new TreeNode(6);
treeNode5.setRightNode(treeNode6);
treeNode2.setLefTreeNode(treeNode3);
treeNode2.setRightNode(treeNode4);
treeNode1.setLefTreeNode(treeNode2);
treeNode1.setRightNode(treeNode5);
List<Integer>aa=new ArrayList<>();
aa.add(treeNode1.getValue());
aa.addAll(levelOrderTraversal(treeNode1.getLefTreeNode()));
aa.addAll( levelOrderTraversal(treeNode5));
aa.stream().forEach(s-> System.out.println(s));
}
public static List<Integer> levelOrderTraversal(TreeNode treeNode) {
List<Integer>valueList=new ArrayList<>();
LinkedList<TreeNode> q = new LinkedList<>();
TreeNode node=new TreeNode();
q.push(treeNode);
while (!q.isEmpty()) {
node = q.getFirst();
q.pop();
valueList.add(node.getValue());
if (node.getLefTreeNode() != null) {
q.addLast(node.getLefTreeNode());
}
if (node.getRightNode() != null) {
q.addLast(node.getRightNode());
}
}
return valueList;
}
}
我要刷100道算法题,第82道
|