天天看点

[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学杂了容易混乱,再次验证了学精的重要性。