114. Flatten Binary Tree to Linked List(深搜)

package Recursion;

public class Flatten_114 {
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}
	public void flatten(TreeNode root) {
		while(root!=null) {
			// 左子樹爲 null,直接跳到下一個節點
			if(root.left==null) {
				root=root.right;
			}else {
				// 找左子樹最右邊的節點
				TreeNode pre=root.left;
				while(pre.right!=null) {
					pre=pre.right;
				}
				//將原來的右子樹接到左子樹的最右邊節點
				pre.right=root.right;
				// 將左子樹插入到右子樹的地方
				root.right=root.left;
				root.left=null;
				
				root=root.right;
			}
			
		}
	}



}

發佈了93 篇原創文章 · 獲贊 8 · 訪問量 9043
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章