二叉樹的先序,中序,後續的遞迴和非遞迴方式

2021-09-25 20:52:08 字數 2282 閱讀 5095

先序遞迴:

public static void preorderrecur(node head)

system.out.println(head.value + " ");

preorderrecur(head.left);

preorderrecur(head.right);

}

中序遞迴:
public static void inorderrecur(node head)

preorderrecur(head.left);

system.out.println(head.value + " ");

preorderrecur(head.right);

}

後續遞迴
public static void posorderrecur(node head)

preorderrecur(head.left);

preorderrecur(head.right);

system.out.println(head.value + " ");

}

先序非遞迴
public static void preorderunrecur(node head)

}}

中序非遞迴:
public static void inorderunrecur(node head)

else

}}}

後序非遞迴

借用兩個棧,第乙個棧實現根右左的遍歷,然後將遍歷的元素都壓入第二個棧中,這樣第二個棧列印的順序即為左右根。

public static void posorderunrecur(node head)

while(!s2.isempty())

}}

moris實現先序遍歷

class

solution

else

else}}

return res;}}

;

moris實現中序遍歷

public

static

void

morrisin

(node head)

else

cur2.right = null;

} system.out.

print

(cur1.value +

" ")

; cur1 = cur1.right;

}}

層序遍歷

遞迴版本

/**

* definition for a binary tree node.

* struct treenode

* };

*/class

solution

res[level]

.push_back

(root-

>val);if

(root-

>left!=

null

)dfs

(root-

>left, level+1)

;if(root-

>right !=

null

)dfs

(root-

>right, level+1)

;}vectorint>>

levelorder

(treenode* root)

};

迭代版本

class

solution

res.

push_back

(temp);}

return res;}}

;

二叉樹的鋸齒形層次遍歷

給定乙個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。

/**

* definition for a binary tree node.

* struct treenode

* };

*/class

solution

res.

push_back

(temp)

; l2r =

!l2r;

}return res;}}

;

二叉樹的建立,先序 中序 後續遞迴和非遞迴遍歷

shengming.h pragma once include stdafx.h define n 20 typedef char elemtype typedef int status extern int coun typedef struct bnode bnode,btree typedef...

二叉樹的非遞迴先序,中序遍歷

題目描述 從鍵盤接收擴充套件先序序列,以二叉鍊錶作為儲存結構,建立二叉樹。採取非遞迴方法輸出這棵二叉樹的先序 中序遍歷序列。樣例輸入 abc de g f 樣例輸出 abcdegf cbegdfa 實現 include include define max 100 typedef struct no...

二叉樹先序 中序 後序 層序遍歷的遞迴和非遞迴實現

先序 中序 後序三種遞迴遍歷 先序遍歷 void preorder treenode head 中序遍歷 void inorder treenode head 後序遍歷 void postorder treenode head 層序遍歷列印二叉樹的遞迴法 include includeusing n...