标签:
Using DFS to traverse the tree.
4 cases for each node in the tree:
case 1: it‘s a leaf node, set a pointer pointing to the node. We‘re reaching an end of one dfs search.
case 2: has left child, and no right child, set the right child to be left one, and set left to be null, go into new right child.
case 3: no left child, right child exists. Just go directly into the right child.
case 4: both left and right child exist. First, using dfs to traverse the left subtree, retrieve the former leaf pointer, set its right child to be current node‘s right child. And dfs to traverse the right child one.
Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { TreeNode deadend = null; public void flatten(TreeNode root) { if(root == null) return; rotate(root); } public void rotate(TreeNode node){ if(node.left == null && node.right == null) { deadend = node; return; } if(node.left != null && node.right == null){ node.right = node.left; node.left = null; rotate(node.right); } else if(node.left == null && node.right != null) rotate(node.right); else{ TreeNode temp = node.right; node.right = node.left; node.left = null; rotate(node.right); //System.out.println(deadend.val); deadend.right = temp; rotate(deadend.right); } } /* public TreeNode rotate(TreeNode node){ TreeNode deadend = node; TreeNode temp = node.right; if(node.left != null){ node.right = node.left; deadend = rotate(node.left); node.left = null; } if(node.right != null){ deadend.right = temp; deadend = rotate(node.right); } return deadend; } */ }
Jan 29 - Flatten Binary Tree To Linked List; DFS;
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5170462.html