题目
思路
代码
//1.使用栈 public void flatten(TreeNode root) { if (root == null) return; Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { TreeNode cur = stack.pop(); if (cur.right != null) stack.push(cur.right); if (cur.left != null) stack.push(cur.left); cur.right = stack.isEmpty() ? null : stack.peek(); cur.left = null; } } //2.递归 TreeNode prev; public void flatten(TreeNode root) { if (root == null) return; TreeNode right = root.right, left = root.left; if (prev != null) prev.right = root; prev = root; root.left = null; flatten(left); flatten(right); }
二叉树展开为链表