给定一个二叉树,原地将它展开为链表。面试
例如,给定二叉树spa
1 / \ 2 5 / \ \ 3 4 6
将其展开为:指针
1 \ 2 \ 3 \ 4 \ 5 \ 6
这算是比较经典的一道题目了, 博主面试快手的时候原题。最开始一想,以为递归的求解不就行了,可是递归的时候发现须要注意一个地方就是:须要先递归右子树,而后记录下右子树展开完成以后的链表头。而后再递归的求解左子树,把左子树的最后一个链到右子树的链表头。基于这个,咱们用一个pre指针来记录右子树的头结点。code
class Solution { private TreeNode prev = null; public void flatten(TreeNode root) { if (root == null) return; flatten(root.right); flatten(root.left); root.right = prev; root.left = null; prev = root; } }
递归的方式转换为迭代的方式用stack就行了,反而比较好理解。递归
class Solution { public void flatten(TreeNode root) { if (root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while (!stack.isEmpty()) { TreeNode current = stack.pop(); if (current.right != null) stack.push(current.right); if (current.left != null) stack.push(current.left); if (!stack.isEmpty()) current.right = stack.peek(); current.left = null; } } }
有问题加手撕代码QQ群讨论:805423079rem