每天1题算法题(5)- 二叉树展开为链表
给定一个二叉树,原地将它展开为一个单链表。
解答
将二叉树展开为单链表之后,单链表中的节点顺序即为二叉树的前序遍历访问各节点的顺序
递归实现
class Solution { private TreeNode curNode; public void flatten(TreeNode root) { List<TreeNode> treeNodeList = new ArrayList(); preOrder(root, treeNodeList); for(int i=1; i < treeNodeList.size(); i++) { root.right = treeNodeList.get(i); root.left = null; root = root.right; } } private void preOrder(TreeNode node, List<TreeNode> treeNodeList) { if(node == null) { return; } treeNodeList.add(node); preOrder(node.left, treeNodeList); preOrder(node.right, treeNodeList); } }
迭代实现
class Solution { private TreeNode curNode; public void flatten(TreeNode root) { if(root == null) { return; } List<TreeNode> list = new ArrayList(); Stack<TreeNode> stack = new Stack(); stack.push(root); while(!stack.isEmpty()) { TreeNode treeNode = stack.pop(); list.add(treeNode); if(treeNode.right != null){ stack.push(treeNode.right); } if(treeNode.left != null){ stack.push(treeNode.left); } } for(int i=1;i<list.size();i++) { root.right = list.get(i); root.left = null; root = root.right; } } }