1.  minimum-depth-of-binary-tree

题目描述

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.
求二叉树的最小深度;

解题思路

递归遍历二叉树的每一个节点:

(1)如果该节点为null,返回深度为0;

(2)如果节点不为空,返回左,右孩子中较小的那个孩子的深度+1;

注意:在(2)中容易出现的问题是,如果一个节点只有左孩子,没有右孩子,那么此时返回的应该是左孩子的深度,而不应该简单的认为返回两者的最小值;

1 public class Solution {
2     public int run(TreeNode root) {
3         if(root==null)
4             return 0;
5         int right = run(root.right);
6         int left = run(root.left);
7         return (left==0 || right==0)? (left+right+1) : Math.min(left,right)+1;
8     }
9 }

2. binary-tree-postorder-traversal

题目描述

Given a binary tree, return the postorder traversal of its nodes' values. 后序遍历二叉树

For example:
Given binary tree{1,#,2,3},

   1\2/3

return[3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

解题思路:

后序遍历的顺序是:左->右->根,递归的方法很好写:

 1 public class Solution {
 2     ArrayList<Integer> list = new ArrayList<Integer>();
 3     public ArrayList<Integer> postorderTraversal(TreeNode root) {
 4         if(root==null)
 5             return list;
 6         if(root.left!=null)
 7             postorderTraversal(root.left);
 8         if(root.right!=null)
 9             postorderTraversal(root.right);
10         list.add(root.val);
11         return list;
12     }
13 }

非递归方法,使用栈来迭代:

要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。
(1)如果P不存在左孩子和右孩子,则可以直接访问它;
(2)或者P存在孩子,但是其孩子都已被访问过了,则同样可以直接访问该结点
(3)若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了
注意:每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。
 1 public class Solution {
 2     public ArrayList<Integer> postorderTraversal(TreeNode root) {
 3         ArrayList<Integer> list = new ArrayList<Integer>();
 4         if(root==null)
 5             return list;
 6         Stack<TreeNode> S = new Stack<TreeNode>();
 7         TreeNode preNode = null;
 8         S.push(root);
 9         while(!S.isEmpty()){
10             TreeNode curNode = S.peek();
11             if((curNode.left==null && curNode.right==null)||
12                (preNode != null && (preNode == curNode.left || preNode == curNode.right))){
13                 list.add(curNode.val);
14                 S.pop();
15                 preNode = curNode;
16             }
17             else{
18                 if(curNode.right!=null)
19                     S.push(curNode.right);
20                 if(curNode.left!=null)
21                     S.push(curNode.left);
22             }
23         }
24         return list;
25     }
26 }

3. binary-tree-preorder-traversal

题目描述

Given a binary tree, return the preorder traversal of its nodes' values. 非递归前序遍历二叉树

For example:
Given binary tree{1,#,2,3},

   1\2/3 

return[1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

解题思路:

利用栈的结构,先序遍历的顺序为 根左右,根先进栈,每次从栈中弹出一个节点访问,并把它的孩子(不为空)按先右后左的顺序入栈,直到栈为空;
 1 public class Solution {
 2     public ArrayList<Integer> preorderTraversal(TreeNode root) {
 3         Stack<TreeNode> S = new Stack<TreeNode>();
 4         ArrayList<Integer> list = new ArrayList<Integer>();
 5         if(root==null){
 6             return list;
 7         }
 8         S.push(root);
 9         while(!S.isEmpty()){
10             TreeNode tmp = S.pop();
11             list.add(tmp.val);
12             if(tmp.right!=null)
13                 S.push(tmp.right);
14             if(tmp.left!=null)
15                 S.push(tmp.left);
16         }
17         return list;
18     }
19 }

4. sum-root-to-leaf-numbers

题目描述

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1/ \2   3

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

从根节点到二叉树的叶子节点的每一条路径都有可以用一个数字表示,求这些数字的和;

解题思路:

用递归来做,主要就是考虑递归条件和结束条件。递归条件即是把当前的sum乘以10并且加上当前节点传入下一函数,进行递归,最终把左右子树的总和相加。结束条件的话就是如果一个节点是叶子,那么我们应该累加到结果总和中,如果节点到了空节点,则不是叶子节点,不需要加入到结果中,直接返回0即可。本质是一次先序遍历。

 1 public class Solution {
 2     public int sumNumbers(TreeNode root) {
 3         return Count(root, 0 );
 4     }
 5     static int Count(TreeNode root,int sum){
 6         if(root==null)
 7             return 0;
 8         if(root.left==null&&root.right==null)
 9             return sum*10+root.val;
10         return Count(root.left,sum*10+root.val)+Count(root.right,sum*10+root.val);
11     }
12 }

5. binary-tree-maximum-path-sum

题目描述

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1/ \2   3

Return 6.

找到二叉树中和最大的一条路径(任意节点为起点,不是根节点,不重复,不相交)

解题思路:

从根节点出发,递归地去找每个节点的左右子树的最大和的路径,返回当前节点的值+左右子树中和较大的那个;

注意,遍历每一条可能的路径时,都要更新最大和是否小于当前这条路径的和,是则更新;

 1 public class Solution {
 2     public int sum = Integer.MIN_VALUE;
 3     public int maxPathSum(TreeNode root) {
 4         if(root==null)
 5             return 0;
 6         max(root);
 7         return sum;
 8     }
 9     public int max(TreeNode root){
10         if(root==null)
11             return 0;
12         int left = Math.max(0, max(root.left));
13         int right = Math.max(0, max(root.right));
14         sum = Math.max(sum, left+right+root.val);
15         return Math.max(left, right)+root.val;
16     }
17 }

6. populating-next-right-pointers-in-each-node

题目描述

Given a binary tree

    struct TreeLinkNode {TreeLinkNode *left;TreeLinkNode *right;TreeLinkNode *next;}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.

Initially, all next pointers are set toNULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

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

After calling your function, the tree should look like:

         1 -> NULL/  \2 -> 3 -> NULL/ \  / \4->5->6->7 -> NULL

解题思路

由于是完全二叉树,所以每一个节点如果有左孩子,一定有右孩子,所以左孩子的next指向右孩子,右孩子的next指向其父节点next的左孩子(如果父节点不为空),如果父节点的next为空,则他也指向空;所以,如果我们知道每一层最左边的节点,那么就可以获得下一层的第一个节点以及下一层所有节点的父节点;
 1 public class Solution {
 2     public void connect(TreeLinkNode root) {
 3         if(root==null)
 4             return;
 5         root.next = null;
 6         TreeLinkNode node = root, next = node;
 7         while(node.left!=null){
 8             next = node;
 9             while(next!=null){
10                 next.left.next = next.right;
11                 if(next.next!=null)
12                     next.right.next = next.next.left;
13                 next = next.next;
14             }
15             node = node.left;
16         }
17     }
18 }

7. populating-next-right-pointers-in-each-node-ii

题目描述

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1/  \2    3/ \    \4   5    7

After calling your function, the tree should look like:

         1 -> NULL/  \2 -> 3 -> NULL/ \    \4-> 5 -> 7 -> NULL

题目描述

与上题不同,给定的二叉树不一定是完全二叉树;采用递归的方法,对于每一层,dummy指向每一层的第一个节点,对该层的每一个节点,处理它的孩子的next指向:如果它有左孩子,那么prev的next就为当前节点的左孩子,并标记左孩子为prev;如果它有右孩子,那么prev的next就为当前节点的右孩子,并标记右孩子为prev;这样,无论是否是完全二叉树,都能实现next的正确指向。
 1 public class Solution {
 2     public void connect(TreeLinkNode root) {
 3         if(root == null)
 4             return;
 5         TreeLinkNode dummy = new TreeLinkNode(-1);
 6         TreeLinkNode cur;
 7         TreeLinkNode prev = dummy;
 8         for(cur=root; cur !=null; cur = cur.next){
 9             if(cur.left !=null)
10             {
11                 prev.next = cur.left;
12                 prev = prev.next;
13             }
14             if(cur.right !=null){
15                 prev.next = cur.right;
16                 prev = prev.next;
17             }
18         }
19         connect(dummy.next);
20     }
21 }

8. path-sum

题目描述

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 andsum = 22,

              5/ \4   8/   / \11  13  4/  \      \7    2      1

return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.

解题思路

采用递归的思想:如果当前节点是叶子节点,且该节点的val等于sum,则返回true;

否则,递归第去判断该节点的左子树或者右子树的和是否满足sum-val。

1 public class Solution {
2     public boolean hasPathSum(TreeNode root, int sum) {
3         if(root==null)
4             return false;
5         if(root.left==null && root.right==null && root.val==sum)
6             return true;
7         return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);
8     }
9 }

9. path-sum-ii

题目描述

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree andsum = 22,

              5/ \4   8/   / \11  13  4/  \    / \7    2  5   1

return

[[5,4,11,2],[5,8,4,5]
]找到路径和为sum的所有路径

解题思路

判断方法和上一题一样,关键是路径的存储

 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
 3         ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
 4         if(root==null)
 5             return list;
 6         ArrayList<Integer> ls = new ArrayList<Integer>();
 7         find(list,ls,root,sum);
 8         return list;
 9     }
10     static void find(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> ls, TreeNode root, int sum){
11         if(root==null)
12             return;
13         ls.add(root.val);
14         if(root.left==null && root.right==null && root.val==sum){
15             list.add(ls);
16         }
17         find(list,new ArrayList<Integer>(ls),root.left, sum-root.val);
18         find(list,new ArrayList<Integer>(ls),root.right, sum-root.val);
19     }
20 }

10. 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.

解题思路

递归地判断每颗子树是否为高度平衡二叉树(任一节点的左右子树高度差不超过1)

 1 public class Solution {
 2     public boolean isBalanced(TreeNode root) {
 3         if(root==null)
 4             return true;
 5         if(Math.abs(getDepth(root.left)-getDepth(root.right))>1)
 6             return false;
 7         return (isBalanced(root.left) && isBalanced(root.right));
 8     }
 9     public int getDepth(TreeNode root){
10         if(root==null)
11             return 0;
12         return 1+Math.max(getDepth(root.left),getDepth(root.right));
13     }
14 }

11. binary-tree-level-order-traversal

题目描述

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree{3,9,20,#,#,15,7},

    3/ \9  20/  \15   7

return its level order traversal as:

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

解题思路

二叉树的层次遍历,用广度优先搜索,采用队列实现

 1 import java.util.*;
 2 public class Solution {
 3     public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
 4         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 5         if(root == null){
 6             return res;
 7         }
 8         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 9         queue.offer(root);
10         while(!queue.isEmpty()){
11             ArrayList<Integer> arr = new ArrayList<Integer>();
12             int size = queue.size();
13             TreeNode p = queue.peek();
14             for(int i=0;i<size;i++){
15                 if(queue.peek().left!=null)
16                     queue.offer(queue.peek().left);
17                 if(queue.peek().right!=null)
18                     queue.offer(queue.peek().right);
19                 arr.add(queue.poll().val);
20             }
21             res.add(arr);
22         }
23         return res;
24     }
25 }

12. binary-tree-level-order-traversal-ii

解题思路

  与上题类似,只不过每层的数据按从底向上输出,仍然按照上题的方法遍历二叉树,但是每层的结果保存在一个栈中,最后按出栈顺序保存在list里;

 1 import java.util.*;
 2 public class Solution {
 3     public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
 4         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 5         Stack<ArrayList<Integer>> stack = new Stack<ArrayList<Integer>>();
 6         if(root==null)
 7             return res;
 8         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 9         queue.offer(root);
10         while(!queue.isEmpty()){
11             ArrayList<Integer> arr = new ArrayList<Integer>();
12             int size = queue.size();
13             for(int i=0;i<size;i++){
14                 if(queue.peek().left!=null)
15                     queue.offer(queue.peek().left);
16                 if(queue.peek().right!=null)
17                     queue.offer(queue.peek().right);
18                 arr.add(queue.poll().val);
19             }
20             stack.push(arr);
21         }
22         while(!stack.isEmpty()){
23             res.add(stack.pop());
24         }
25         return res;
26     }
27 }

13. binary-tree-zigzag-level-order-traversal

解题思路

Z字形层次遍历二叉树

与上题类似,添加一个标志,如果是偶数层,反转该层的元素即可

 1 import java.util.*;2 public class Solution {3     public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {4         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();5         if(root == null){6             return res; 7  } 8 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 9  queue.offer(root); 10 boolean reserve = true; 11 while(!queue.isEmpty()){ 12 reserve = !reserve; 13 ArrayList<Integer> arr = new ArrayList<Integer>(); 14 int size = queue.size(); 15 TreeNode p = queue.peek(); 16 for(int i=0;i<size;i++){ 17 if(queue.peek().left!=null) 18  queue.offer(queue.peek().left); 19 if(queue.peek().right!=null) 20  queue.offer(queue.peek().right); 21  arr.add(queue.poll().val); 22  } 23 if(reserve){ 24 int len = arr.size(); 25 int t = len/2; 26 for(int i=0;i<t;i++){ 27 Collections.swap(arr,i,len-1-i); 28  } 29  } 30  res.add(arr); 31  } 32 return res; 33  } 34 }

14. maximum-depth-of-binary-tree

解题思路

  求二叉树的最大深度

  递归求左右子树的最大深度,每个节点的最大深度为左右子树的最大深度+1(自身)

1 public class Solution {
2     public int maxDepth(TreeNode root) {
3         return root == null ? 0 : (1 + Math.max(maxDepth(root.left), maxDepth(root.right)));
4     }
5 }

15. symmetric-tree

给定一棵二叉树,判断其是否为对称的二叉树

解题思路

  递归判断左右子树是否完全相同即可

 1 public class Solution {
 2     public boolean isSymmetric(TreeNode root) {
 3         if(root==null)
 4             return true;
 5         return judge(root.left,root.right);
 6     }
 7     private static boolean judge(TreeNode a,TreeNode b){
 8         if(b==null && a==null)
 9             return true;
10         else if((a==null && b!=null) || (a!=null && b==null))
11             return false;
12         else
13             return (a.val==b.val && judge(a.left,b.right) && judge(a.right,b.left));
14     }
15 }

16. same-tree

判断两棵树是否完全相同

解题思路

  递归判断两个数的左子树是否完全相同且右子树完全相同

1 public class Solution {
2     public boolean isSameTree(TreeNode p, TreeNode q) {
3         if(p==null && q==null)
4             return true;
5         if( (p==null && q!=null) || (p!=null && q==null))
6             return false;
7         return (p.val==q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right));
8     }
9 }

转载于:https://www.cnblogs.com/PJQOOO/p/10978662.html

LeetCode 刷题笔记 (树)相关推荐

  1. 渣渣的leetcode刷题笔记-树(1)

    这两天在做tree的题目(easy),基本上每道都实现了**recursive**和**iterative**两种解法,简单整理一下. 感想: 能用BFS+queue解决的基本都可以用DFS+stac ...

  2. 卷进大厂系列之LeetCode刷题笔记:二分查找(简单)

    LeetCode刷题笔记:二分查找(简单) 学算法,刷力扣,加油卷,进大厂! 题目描述 涉及算法 题目解答 学算法,刷力扣,加油卷,进大厂! 题目描述 力扣题目链接 给定一个 n 个元素有序的(升序) ...

  3. leetcode刷题之树(三)

    翻转二叉树,感觉做二叉树的问题好像都是那一套公式,除了个别的问题解决不了,用上篇博客leetcode刷题之树(二)的模型基本可以解决.总体来说就是树基本都可以利用递归和迭代的方法去解决,在涉及到树的遍 ...

  4. LeetCode刷题笔记2——数组2

    LeetCode刷题笔记2--数组2 重塑数组 题目 在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原 ...

  5. 小何同学的leetcode刷题笔记 基础篇(01)整数反转

    小何同学的leetcode刷题笔记 基础篇(01)整数反转[07] *** [01]数学取余法*** 对数字进行数位操作时,常见的方法便是用取余的方法提取出各位数字,再进行操作 操作(1):对10取余 ...

  6. LeetCode刷题笔记汇总

    LeetCode刷题笔记汇总 第一次刷LeetCode写的一些笔记. 1.两数之和 3.无重复字符的最长子串 15.三数之和 18.四数之和 19.删除链表的倒数第 N 个结点 20.有效的括号 21 ...

  7. 【leetcode刷题笔记】动态规划

    #[leetcode刷题笔记]动态规划 石子游戏 public boolean stoneGame(int[] piles) {int N = piles.length;// dp[i][j] is ...

  8. LeetCode刷题笔记-动态规划-day4

    文章目录 LeetCode刷题笔记-动态规划-day4 55. 跳跃游戏 1.题目 2.解题思路 3.代码 45. 跳跃游戏 II 1.题目 2.解题思路 3.代码 LeetCode刷题笔记-动态规划 ...

  9. LeetCode刷题笔记- 15.三数之和

    LeetCode刷题笔记- 15.三数之和 C语言 题目 注意点 C语言 /*** Return an array of arrays of size *returnSize.* The sizes ...

  10. LeetCode刷题笔记第6题:Z字形变换

    LeetCode刷题笔记第6题:Z字形变换 想法: 要完成字符串根据给定的行数从上往下,从左到右完成Z字形排列.当只有一行时直接返回原字符串,当行数大于1时,先以行数构建一个行数数值个空字符串的列表, ...

最新文章

  1. SpringBoot05 数据操作01 - JPA的基本使用、基本使用02
  2. golang map 初始化 和 使用
  3. 一维卷积filter_面试题:CNN的卷积核是单层的还是多层的?
  4. Android GraphicBuffer
  5. 一文解开java中字符串编码的小秘密
  6. solr cloud 更新 solrconfig 配置_Solr各版本新特性「4.x,5.x,6.x,7.x」
  7. Ubuntu中输入输出重定向及管道技术简述
  8. hashMap 底层原理+LinkedHashMap 底层原理+常见面试题
  9. 如何调位置_如何获得正确的驾驶坐姿?
  10. Atitit. Derby的使用总结attilax
  11. [转] 字符编码笔记:ASCII,Unicode和UTF-8
  12. SpringBoot整合腾讯云直播,生成推拉流配置及工具类详细讲解!
  13. android als传感器,环境光传感器(ALS)背光控制解决方案
  14. 计算机ms高级应用科目一 科目二考什么,驾考提前知 | 科目一、科目二、科目三、科目四都考什么?...
  15. 计算机可靠度计算公式,可靠性计算公式大全
  16. Java根据IP返回 省市,
  17. 为什么你的广告投放效果不好?这5点做到了吗?
  18. mac m1使用picGo + gitee搭建免费图床
  19. 关于Socket中端口复用(udp)
  20. 拾人牙慧,浅记一些C++的类

热门文章

  1. android handler封装_Handler都没搞懂,你拿什么去跳槽啊?!
  2. 每日一题(25)—— 自加++
  3. android导出apk文件_Android测试工具入门介绍(三)
  4. 添加python的系统路径_如何将项目路径添加到系统路径永久地?
  5. ValueError: Found array with dim 4. Estimator expected和ValueError: Expected 2D array, got 1D array i
  6. Ajax 编程基础(一)
  7. Chapter1-2_Speech_Recognition(LAS)
  8. LeetCode 1891. 割绳子(二分查找)
  9. LeetCode 935. 骑士拨号器(动态规划)
  10. 程序员面试金典 - 面试题 02.03. 删除中间节点