leetcode 114. 二叉树展开为链表
给你二叉树的根结点 root ,请你将它展开为一个单链表:
展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。
示例 1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [0]
输出:[0]
提示:
树中结点数在范围 [0, 2000] 内
-100 <= Node.val <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
采用递归,前序遍历。
public void flatten(TreeNode root) { if (root == null) { return; } TreeNode a = new TreeNode(0); find(root, a); } private static TreeNode find(TreeNode node, TreeNode f) { f.right = node; TreeNode returnNode = node; TreeNode l = node.left; TreeNode r = node.right; node.left = null; node.right = null; if (l != null) { returnNode = find(l, node); } if (r != null) { returnNode = find(r, returnNode); } return returnNode; }
public void flatten(TreeNode root) { if (root == null) { return; } TreeNode a = new TreeNode(0); Stack<TreeNode> stack = new Stack<>(); stack.add(root); while (!stack.isEmpty()) { TreeNode pop = stack.pop(); a.right = pop; if (pop.right != null) { stack.add(pop.right); } if (pop.left != null) { stack.add(pop.left); } a = pop; pop.left = null; pop.right = null; } }