及其重要
public static void f(Node head){
if (head == null) {
return ;
}
// 1
f(head.left);
// 2
f(head.right);
// 3
}
深刻理解,一个节点会遍历三次,1位置,2位置,3位置按照顺序执行下去的话,是一定会经过的,也就是一个节点一定会走3次。
递归递归,就是一次次的方法进栈和出栈。
Leetcode94
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
ArrayList<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return list;//这里什么都不干,把方法出栈
}
inorderTraversal(root.left);
// 这里是中序
list.add(root.val);
inorderTraversal(root.right);
return list; //返回结果,把方法出栈
}
}
二叉树的递归套路
1.加速以X节点为头,假设可以向X左树和X右树要任何信息
2.在上一步的假设下,讨论以X为头节点的树,得到答案的可能性(最重要)
3.列出所有可能性后,确定到底需要向左树和右树要什么样的信息
4.把左树信息和右树信息求全集,就是任何一个子树都需要返回的信息S
5.递归函数都返回S,每一颗子树都这么要求
6.写代码,在代码中考虑如何把左树的信息和右树的信息整合出整颗树的信息
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
boolean flag = true;
public boolean isSameTree(TreeNode p, TreeNode q) {
// base case
if (p == null && q == null) {
return true;
} else if (p == null || q == null) {
return false;
}
// 递归
boolean left = isSameTree(p.left,q.left);
boolean right = isSameTree(p.right,q.right);
//当前节点答案的可能性
if (left && right && p.val == q.val) {
flag = true;
} else {
flag = false;
}
return flag;
}
}
leetcode101
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return isS(root,root);
}
public boolean isS(TreeNode t1,TreeNode t2) {
// base case
if (t1==null && t2==null) {
return true;
} else if (t1==null || t2==null) {
return false;
}
// 递归遍历
boolean left = isS(t1.left,t2.right);
boolean right = isS(t1.right,t2.left);
// 问题可能性求解
if (t1.val == t2.val && left && right) {
return true;
} else {
return false;
}
}
}