【LeetCode】Flatten Binary Tree to Linked List

HIT_微笑前進發表於2015-03-28

題目:Flatten Binary Tree to Linked List

<span style="font-size:18px;">/**LeetCode Flatten Binary Tree to Linked List
 * 題意:給定一個二叉樹,將其轉變為一個相當於單連結串列的結構,觀察可知該結構即:每一個節點左兒子為空,右兒子指向自己先序遍歷時的下一個節點
 * 思路:有觀察可得,應對其進行先序遍歷,得到正確的序列連線起來
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */ 
package javaTrain;

public class Train18 {
	public void flatten(TreeNode root) {
		if(root== null || (root.left == null && root.right == null)) return;
		preOrder(root);
		return;
    }
	private TreeNode preOrder(TreeNode root){
		if(root== null || (root.left == null && root.right == null)) return root;
		TreeNode left = root.left;
		TreeNode right = root.right;
		TreeNode last;
		root.left = null; 
		if(left != null){
			root.right = left;
			last = preOrder(left);
			last.left = null;
			if(right != null){
				last.right = right;
				return preOrder(right);
			}
			else return last;
		}
		else{
			root.right = right;
			return preOrder(right);
		}
	}
}
</span>


相關文章