翻轉二叉樹

2022-06-12 18:45:10 字數 543 閱讀 3872

invert a binary tree.

4

/ \

2 7

/ \ / \

1 3 6 9

to

4

/ \

7 2

/ \ / \

9 6 3 1

思路:採取先序遍歷,根》左子樹》右子樹,自上而下分別把結點的左子樹和右子樹翻轉,例如,結點4的左子樹2和右子樹7調換

4

/ \

7 2

/ \ / \

6 9 1 3

再依次呼叫inverttree函式傳左子樹和右子樹進去。.....

**如下:

1/**

2* definition for a binary tree node.

3* struct treenode ;8*/

9struct treenode* inverttree(struct treenode*root)

翻轉二叉樹

問題描述 翻轉一棵二叉樹 樣例 1 1 2 3 3 2 4 4 實現思路 從根出發開始操作,如果要操作的節點是空值,則不進行任何操作 否則,交換左右兒子,這裡新建乙個temp變數作為過渡。然後利用遞迴演算法,分別對左右子樹進行處理。實現 definition of treenode class tr...

翻轉二叉樹

目錄當前節點不為空則交換左右子節點,遞迴非常直觀。func inverttree1 root treenode treenode return root 該方法類似樹的層次遍歷,出隊元素交換左右子節點,當前節點左右不為空則入隊。func inverttree2 root treenode treen...

(二叉樹)226 翻轉二叉樹

翻轉一棵二叉樹。其實就是交換一下左右節點,然後再遞迴的交換左節點,右節點 根據動畫圖我們可以總結出遞迴的兩個條件如下 終止條件 當前節點為null時返回 交換當前節點的左右節點,再遞迴的交換當前節點的左節點,遞迴的交換當前節點的右節點 class solution 下面三句是將當前節點的左右子樹交換...