一、二叉樹物件
public class node
public node(string value)
}
二、遞迴遍歷
遞迴過程中每個節點到達三次,存在前中後三種順序。時間複雜度o(n),空間複雜度o(n)
2.1 前序遍歷
public static void preorder(node head)
system.out.print(head.value);
preorder(head.left);
preorder(head.right);
}
2.2 中序遍歷
public static void midorder(node head)
midorder(head.left);
system.out.print(head.value);
midorder(head.right);
}
2.3 後續遍歷
public static void afterorder(node head)
afterorder(head.left);
afterorder(head.right);
system.out.print(head.value);
}
三、非遞迴方式
前序遍歷與中序遍歷需要基於棧結構。後續遍歷使用到兩個棧結構。時間複雜度o(n),空間複雜度o(n)
3.1 前序遍歷
public static void preorderbystack(node head)
if(node.left != null)
}}
3.2 中序遍歷
public static void midorderbystack(node head) else
}}
3.3 後續遍歷
public static void afterorderbystack(node head)
if(head.right != null)
}while (!result.empty())
}
四、按層遍歷
按層遍歷使用到輔助佇列,時間空間複雜度為o(n)
public static string serialbylevel(node head)
string res = head.value + "!";
queuequeue = new linkedlist<>();
queue.offer(head);
while (!queue.isempty()) else
if (head.right != null) else
}return res;
}
五、morris遍歷
morris遍歷時間複雜度o(n),空間複雜度o(1)
三條原則:
1、current節點如果沒有左孩子,current向右移
2、current節點有左孩子,找到左子樹的最右節點記為mostright,如果mostright的右指標為空,讓其指向current,current向左移。
3、如果mostright的右指標為current,讓其為空,current向右移動。
5.1 前序遍歷
public static void morrispre(node head)
node current = head;
node mostright = null;
while (current != null)
if (mostright.right == null) else
} else
current = current.right;
} system.out.println();
}
5.2 中序遍歷
public static void morrisin(node head)
node cur1 = head;
node cur2 = null;
while (cur1 != null)
if (cur2.right == null) else
}system.out.print(cur1.value + " ");
cur1 = cur1.right;
} system.out.println();
}
5.3 後續遍歷
public static void morrispos(node head)
node cur1 = head;
node cur2 = null;
while (cur1 != null)
if (cur2.right == null) else
}cur1 = cur1.right;
} printedge(head);
system.out.println();
} public static void printedge(node head)
reverseedge(tail);
} public static node reverseedge(node from)
return pre;
}
二叉樹遍歷方式
先序遍歷 根 左子樹 右子樹 遞迴版本 public static void preprint treenode root 非遞迴版本 public static void preorder treenode root if s.empty 中序遍歷 左子樹 根 右子樹 遞迴版本 public st...
重建二叉樹 遍歷二叉樹的三種方式
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。示例 前序遍歷 preorder 3,9,20,15,7 中序遍歷 inorder 9,3,15,20,7 返回如下的二叉樹 3 9 20 15 7限制 0 節點個數 5000 這個題的解法...
二叉樹四種遍歷方式
二叉樹的四種遍歷方式 include include using namespace std 二叉樹節點的定義 class treenode 遞迴方式,每個結點只遍歷一次,時間複雜度o 1 遞迴最多呼叫n次,空間複雜度o n 先序 根 遞迴左 遞迴右 void preorder treenode r...