Flatten Binary Tree to Linked List
题目地址:
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/#/description
The flattened tree should look like:
题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1
/ \
2 5
/ \ \
3 4 6
1
\
2
\
3
\
4
\
5
\
6
解题思路:
这道题常规解法是用stack来存right child。
代码:
public void flatten(TreeNode root) { TreeNode curr = root; Stack<TreeNode> stack = new Stack<>(); while(!stack.isEmpty() || curr != null){ if(curr.right != null){ stack.push(curr.right); } if(curr.left != null){ curr.right = curr.left; } else{ if(!stack.isEmpty()){ curr.right = stack.pop(); } } curr.left = null; curr = curr.right; } }

Comments
Post a Comment