LeetCode DFS(上)
LeetCode上目前关于DFS的题目有19个,其中有18道是二叉树相关的,只有一道是图方面的。DFS系列解题报告按难度分为上中下三部分,下面是第一部分Easy.
TreeNode结构
#1.Symmetric Tree ref
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
###Recursive Solution
###Iterative Solution
#2.Same Tree ref
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
###Recursive Solution
关于二叉树的一些题目,我的一个心得就是递归,简单明了,迭代算法相对繁琐,如Symmetric Tree,迭代算法用了40行代码,而递归仅仅用了15行代码。这个题目用递归核心就3行代码,不再给出迭代解法。
#3.Balanced Binary Tree ref
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
下面这个解法还可以优化,通过封装TreeNode结点,添加一个表示结点高度的变量,可以避免子问题重复求解;或者用一个map<TreeNode*, int>来保存每个节点的高度。
#4.Minimum Depth of Binary Tree ref
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
#5.Maximum Depth of Binary Tree ref
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
#6.Path Sum ref
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
留下评论