題目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
題解:
如hint所給出,這道題就是使用先序遍歷,遍歷到的值作為新的右孩子存起來,左孩子變為空。
注意的是,因為右孩子會更新,所以為了遞迴右子樹,要在更新之前提前儲存右孩子。
整個程式需要維護一個全域性變數,儲存當前所遍歷的節點。
程式碼如下:
1 TreeNode lastvisited = null;
2 public void flatten(TreeNode root) {
3 if(root == null)
4 return;
5
6 TreeNode realright = root.right;
7 if(lastvisited != null){
8 lastvisited.left = null;
9 lastvisited.right = root;
10 }
11
12 lastvisited = root;
13 flatten(root.left);
14 flatten(realright);
15 }
2 public void flatten(TreeNode root) {
3 if(root == null)
4 return;
5
6 TreeNode realright = root.right;
7 if(lastvisited != null){
8 lastvisited.left = null;
9 lastvisited.right = root;
10 }
11
12 lastvisited = root;
13 flatten(root.left);
14 flatten(realright);
15 }
Reference:http://blog.csdn.net/perfect8886/article/details/20000083
此題還有不用遞迴方法解決的方法,那就是使用棧。
對整棵樹一直向右子樹方向遍歷。當遍歷的節點有右孩子時,就將其入棧。有左孩子時,將其更新為當前節點的右孩子,左孩子置空。當左孩子為空時而棧不空時,
就彈出棧,作為右孩子。程式碼如下:
1 public void flatten(TreeNode root) {
2 Stack<TreeNode> stack = new Stack<TreeNode>();
3 TreeNode p = root;
4
5 while(p != null || !stack.empty()){
6
7 if(p.right != null){
8 stack.push(p.right);
9 }
10
11 if(p.left != null){
12 p.right = p.left;
13 p.left = null;
14 }else if(!stack.empty()){
15 TreeNode temp = stack.pop();
16 p.right=temp;
17 }
18
19 p = p.right;
20 }
21 }
2 Stack<TreeNode> stack = new Stack<TreeNode>();
3 TreeNode p = root;
4
5 while(p != null || !stack.empty()){
6
7 if(p.right != null){
8 stack.push(p.right);
9 }
10
11 if(p.left != null){
12 p.right = p.left;
13 p.left = null;
14 }else if(!stack.empty()){
15 TreeNode temp = stack.pop();
16 p.right=temp;
17 }
18
19 p = p.right;
20 }
21 }
Reference: //http://www.programcreek.com/2013/01/leetcode-flatten-binary-tree-to-linked-list/