Flatten Binary Tree to Linked List ---LeetCode
2016-11-29 10:40
281 查看
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
解题思路:
遍历一遍树,如果根节点的右子节点不为空,将其入栈,并将左子节点移到右边,左边制空。当移到叶子节点时,再将栈里的节点依次弹出。
还有一种利用后序遍历递归的解法:
https://discuss.leetcode.com/topic/11444/my-short-post-order-traversal-java-solution-for-share
解题思路:
遍历一遍树,如果根节点的右子节点不为空,将其入栈,并将左子节点移到右边,左边制空。当移到叶子节点时,再将栈里的节点依次弹出。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public void flatten(TreeNode root) { if (root == null) return ; Stack<TreeNode> stack = new Stack<>(); while (root != null || !stack.isEmpty()) { if (root.right != null) { stack.push(root.right); } if (root.left != null) { root.right = root.left; root.left = null; } else if (!stack.isEmpty()) { root.right = stack.pop(); } root = root.right; } } }
还有一种利用后序遍历递归的解法:
https://discuss.leetcode.com/topic/11444/my-short-post-order-traversal-java-solution-for-share
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; }
相关文章推荐
- LeetCode - Flatten Binary Tree to Linked List
- LeetCode-Flatten Binary Tree to Linked List
- leetcode Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- [leetcode]Flatten Binary Tree to Linked List
- leetcode--Flatten Binary Tree to Linked List
- [Leetcode] Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- [Leetcode]Flatten Binary Tree to Linked List
- [leetcode] Flatten Binary Tree to Linked List
- leetcode - Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- 【leetcode】Flatten Binary Tree to Linked List
- leetcode: Flatten Binary Tree to Linked List
- [LeetCode]Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- [leetcode]Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List