【二叉树】常用处理与leetcode相关题目总结

来源:互联网 发布:javascript常用事件 编辑:程序博客网 时间:2024/06/07 05:08

前言:

这学期刷leetcode时碰到了不少二叉树的题目,以前一看到二叉树就头疼,于是乎也算做了很多这方面的题了,是时候整理一波了。

本篇博客主要是围绕leetcode上关于树的题目展开的,其中也穿插一些二叉树的基本知识,如前序、中序、后序遍历的递归非递归遍历,广度优先搜索和深度优先搜索,层次遍历,结合栈和队列的应用等。

语言方面用Python和C++两种语言各实现了一遍。

以下,正文。


111. Minimum Depth of Binary Tree

题目链接

111.1 题目描述:

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.

111.2 解题思路:

  1. 思路一:递归。如果当前节点为空,则返回0;如果当前节点的左右子节点都为空,则返回1;如果左节点为空,右节点不空,则返回1+进入右节点深度计算;如果右节点为空,左节点不空,则返回1+进入左节点深度计算;如果左右节点都不空,则分别进入左右节点深度计算,并返回1+较小深度的那个。

  2. 思路二:同思路一差不多,进行了优化。如果当前节点为空,则返回0;计算右节点深度和左节点深度;如果左节点为空,返回1+右节点深度;如果右节点为空,返回1+左节点深度。最后返回1+较少深度的那个。

  3. 思路三:同思路二差不多,但是超时了。如果当前节点为空,则返回0;如果左节点为空,返回1+右节点深度;如果右节点为空,返回1+左节点深度。最后返回1+较少深度的那个(这里又递归计算了一遍,存在时间浪费)。

111.3 C++代码:

1、思路一代码(6ms):

class Solution108 {public:    int subdepth(TreeNode *p)    {           int dep = 1;        if (p->left == NULL && p->right == NULL)            return 1;        else if (p->left == NULL && p->right != NULL)            return dep + subdepth(p->right);        else if (p->left != NULL && p->right == NULL)            return dep + subdepth(p->left);        else        {            int dleft = dep + subdepth(p->left);            int dright = dep + subdepth(p->right);            return dleft < dright ? dleft : dright;        }    }    int minDepth(TreeNode* root) {        if (root == NULL)            return 0;        return subdepth(root);    }};

2、思路二代码(6ms):

lass Solution108_1 {public:    int minDepth(TreeNode* root) {        if (root == NULL)            return 0;        int dl=minDepth(root->left);        int dr=minDepth(root->right);        if (dl == 0)            return dr + 1;        if (dr == 0)            return dl + 1;        return dl < dr ? dl+1 : dr+1;    }};

3、思路三代码(超时)

class Solution108_2 {//超时public:    int minDepth(TreeNode* root) {        if (root == NULL)            return 0;        if (root->left == NULL)            return 1 + minDepth(root->right);        if (root->right == NULL)            return 1 + minDepth(root->left);        return minDepth(root->left)<minDepth(root->right) ? minDepth(root->left)+1 : minDepth(root->right)+1;    }};

111.4 Python代码:

2、思路二代码(79ms)

class Solution(object):    def minDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        if root==None:            return 0        dl=self.minDepth(root.left)        dr=self.minDepth(root.right)        if dl==0:            return 1+dr        if dr==0:            return 1+dl        return 1+min(dl,dr)

112. Path Sum

题目链接

112.1 题目描述:

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.

112.2 解题思路:

  1. 思路一:递归,首先判断节点是否为空,若为空,则直接返回false。如果节点恰好是叶子节点,且该节点的值恰好为sum,则返回true,否则,则进入递归,分别判断该节点的左右子树,且此时的sum变为sum-此节点的值。因为只有有一条路存在即可,所以是或操作。

112.3 C++代码:

1、思路一代码(12ms):

class Solution103 {public:    bool hasPathSum(TreeNode* root, int sum) {        if (root == NULL)            return false;        if (root->left==NULL && root->right==NULL && root->val == sum)            return true;        else if (root->left == NULL && root->right == NULL && root->val != sum)            return false;        else            return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);    }};

112.4 Python代码:

1、思路二代码(65ms):

class Solution(object):    def hasPathSum(self, root, sum):        """        :type root: TreeNode        :type sum: int        :rtype: bool        """        if root==None:            return False        if root.left==None and root.right==None and root.val==sum:            return True        elif root.left==None and root.right==None and root.val!=sum:            return False        else:            return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right,sum-root.val)

100.Same Tree

题目链接

题目描述:

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.

解题思路:

C++代码:

Python代码:


101.Symmetric Tree

题目链接

题目描述:

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

   1  / \ 2   2/ \ / \3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

  1 / \2   2\   \3    3

解题思路:

C++代码:

Python代码:


104. Maximum Depth of Binary Tree

题目链接

题目描述:

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.

解题思路:

C++代码:

Python代码:


107. Binary Tree Level Order Traversal II

题目链接

题目描述:

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3   / \  9  20    /  \   15   7

return its bottom-up level order traversal as:

[
[15,7],
[9,20],
[3]
]

解题思路:

C++代码:

Python代码:


108. Convert Sorted Array to Binary Search Tree

题目链接

题目描述:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

解题思路:

C++代码:

Python代码:


110. Balanced Binary Tree

题目链接

题目描述:

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.

解题思路:

C++代码:

Python代码:


226. Invert Binary Tree

题目链接

题目描述:

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9

to

     4   /   \  7     2 / \   / \9   6 3   1

解题思路:

C++代码:

Python代码:


235. Lowest Common Ancestor of a Binary Search Tree

题目链接

题目描述:

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

              6       /              \      2                8   /      \        /      \   0      4       7       9         /  \         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

解题思路:

C++代码:

Python代码:


257. Binary Tree Paths

题目链接

题目描述:

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

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

[“1->2->5”, “1->3”]

解题思路:

C++代码:

Python代码:


404. Sum of Left Leaves

题目链接

题目描述:

Find the sum of all left leaves in a given binary tree.

Example:

    3   / \  9  20    /  \   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

解题思路:

C++代码:

Python代码:


437. Path Sum III

题目链接

题目描述:

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10     /  \    5   3   / \    \  3   2   11 / \   \3  -2   1

Return 3. The paths that sum to 8 are:

  1. 5 -> 3
  2. 5 -> 2 -> 1
  3. -3 -> 11

解题思路:

C++代码:

Python代码:


501. Find Mode in Binary Search Tree

题目链接

题目描述:

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than or equal to the node’s key.

The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.

Both the left and right subtrees must also be binary search trees.

For example:

          1            \             2            /           2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

解题思路:

C++代码:

Python代码:


543. Diameter of Binary Tree

题目链接

题目描述:

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree

              1             / \            2   3           / \               4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

解题思路:

C++代码:

Python代码:


563. Binary Tree Tilt

题目链接

题目描述:

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes’ tilt.

Example:

Input:

     1   /   \  2     3

Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Note:

The sum of node values in any subtree won’t exceed the range of 32-bit integer.
All the tilt values won’t exceed the range of 32-bit integer.

解题思路:

C++代码:

Python代码:


572. Subtree of Another Tree

题目链接

题目描述:

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.

Example 1:

Given tree s:

     3    / \   4   5  / \ 1   2

Given tree t:

   4   / \ 1   2

Return true, because t has the same structure and node values with a subtree of s.

Example 2:

Given tree s:

     3    / \   4   5  / \ 1   2    /   0

Given tree t:

   4  / \ 1   2

Return false.

解题思路:

C++代码:

Python代码:


606. Construct String from Binary Tree

题目链接

题目描述:

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]

   1 /   \2     3/    4     

Output: “1(2(4))(3)”

Explanation: Originallay it needs to be “1(2(4)())(3()())”, but you need to omit all the unnecessary empty parenthesis pairs. And it will be “1(2(4))(3)”.

Example 2:

Input: Binary tree: [1,2,3,null,4]

   1 /   \2     3 \    4 

Output: “1(2()(4))(3)”

Explanation: Almost the same as the first example,
except we can’t omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

解题思路:

C++代码:

Python代码:


617. Merge Two Binary Trees

题目链接

题目描述:

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:

Input:

Tree 1                     Tree 2                        1                         2                                  / \                       / \                                3   2                     1   3                           /                           \   \                        5                             4   7  

Output:

Merged tree:

     3    / \   4   5  / \   \  5   4   7

Note: The merging process must start from the root nodes of both trees.

解题思路:

C++代码:

Python代码:


原创粉丝点击