天天看點

[LeetCode] Binary Tree Paths - 二叉樹基礎系列題目

目錄:

1.binary tree paths - 求二叉樹路徑

2.same tree - 判斷二叉樹相等

3.symmetric tree - 判斷二叉樹對稱鏡像

題目概述:

given a binary tree, return all root-to-leaf paths.

for example, given the following binary tree:

all root-to-leaf paths are:

題目解析:

本題主要考察二叉樹周遊操作,輸出二叉樹的所有路徑,通常采用遞歸方法能很好的解決。但是如果采用c語言編寫,傳回二維字元串數組如何添加二叉樹路徑是個難點?

char** binarytreepaths(struct treenode* root, int* returnsize) {}

最終采用c++完成,當周遊至葉子節點時,通過容器push_back添加一條路徑。

[LeetCode] Binary Tree Paths - 二叉樹基礎系列題目

我的代碼:

推薦代碼:

判斷兩顆二叉樹是否相等,非遞歸方法通過issamenode依次周遊結點

given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

for example, this binary tree is symmetric:

but the following is not:

note:

bonus points if you could solve it both recursively and iteratively.

判斷二叉樹是否為鏡像對稱二叉樹,當時錯誤了解為判斷完全二叉樹。解題思路是通過比較左右結點,左結點->left和右結點->right比較、左結點->right和右結點->left比較。

非遞歸算法可以采用層次周遊,每次比較同一層的數是否鏡像即可。

非遞歸代碼:

ps:二叉樹是面試中經常考察的題目,包括建立二叉樹、周遊二叉樹、二叉樹交換、二叉樹求和等。希望文章對你有所幫助,同時java、c#、c++、c學雜了容易混亂,再次驗證了學精的重要性。