二叉树节点和+递归Java_二叉树根节点到叶子结点的路径:递归与非递归

package 二叉树;

import java.util.*;

public class 二叉树根到叶子节点的路径和 {

public static TreeNode root;

public static Set> set = new HashSet<>();

public static List list = new ArrayList<>();

public static List sum = new ArrayList<>();

public static void createTree(Integer[] objects){

List datas = new ArrayList<>();//存储所有节点

for(Integer obj:objects){

datas.add(new TreeNode(obj));

}

root = datas.get(0);//将一个作为根节点

for(int i = 0;i < objects.length/2;i++){

datas.get(i).left = datas.get(2*i+1);

if(2*i+2 < objects.length){//避免偶数的时候,下标越界

datas.get(i).right = datas.get(2*i+2);

}

}

}

public static void DFS(TreeNode T,int preVal,List list){

if(T!=null){

preVal+=T.val;

list.add(T.val);

if(T.left==null&&T.right==null){

System.out.println(list);

set.add(new ArrayList<>(list));

sum.add(preVal);

}else{

DFS(T.left,preVal,list);

DFS(T.right,preVal,list);

}

//当T是叶子节点,在当前递归状态下需要剔除该元素

list.remove(list.size()-1);

}

}

public static void getPath(TreeNode root,List list,int num){

if(root!=null) {

num+=root.val;

list.add(root.val);

}

if(root.left == null && root.right == null){

System.out.print(num+"=");

System.out.println(list);

sum.add(num);

set.add(new ArrayList<>(list));

}

if(root.left != null)

getPath(root.left,list,num);

if(root.right != null)

getPath(root.right,list,num);

list.remove(list.size()-1);

}

public static List binaryTreePaths(TreeNode root) {

List list=new ArrayList();

Queue queue=new LinkedList();

Queue qStr=new LinkedList();

if (root==null) return list;

queue.add(root);

qStr.add("");

while(!queue.isEmpty()) {

TreeNode curNode=queue.remove();

String curStr=qStr.remove();

if (curNode.left==null && curNode.right==null) list.add(curStr+curNode.val);

if (curNode.left!=null) {

queue.add(curNode.left);

qStr.add(curStr+curNode.val+"->");

}

if (curNode.right!=null) {

queue.add(curNode.right);

qStr.add(curStr+curNode.val+"->");

}

}

return list;

}

public static void main(String[] args) {

Integer[] arr = {1,3,2,4,5,2,1};

createTree(arr);

DFS(root,0,list);

sum.clear();

getPath(root,list,0);

System.out.println(sum);

System.out.println(set);

System.out.println(binaryTreePaths(root));

}

}

你可能感兴趣的:(二叉树节点和+递归Java)