栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

广度优先遍历二叉树(递归二叉树遍历)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

广度优先遍历二叉树(递归二叉树遍历)

题目来自:https://www.programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html#%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E7%A7%8D%E7%B1%BB

文章目录

1. 对称二叉树

101. 对称二叉树100. 相同的树572. 另一棵树的子树 2. 平衡二叉树

110. 平衡二叉树 3. 二叉树路径

257. 二叉树的所有路径404. 左叶子之和513. 找树左下角的值112. 路径总和113. 路径总和 II

1. 对称二叉树 101. 对称二叉树
    递归迭代
	
	public boolean isSymmetric1(TreeNode root) {
		return compare(root.left , root.right);
	}
		
	private boolean compare(TreeNode left, TreeNode right) {
		
		if( left == null && right == null ) return true;
		if( left != null && right == null ) return false;
		if( left == null && right != null ) return false;
		if( left.val != right.val ) return false;
			
		boolean l = compare(left.left, right.right);
		boolean r = compare(left.right, right.left);
		
		return l && r;
	}
	
	
    public boolean isSymmetric3(TreeNode root) {
        Queue deque = new linkedList<>();
        deque.offer(root.left);
        deque.offer(root.right);
        while (!deque.isEmpty()) {
            TreeNode leftNode = deque.poll();
            TreeNode rightNode = deque.poll();
            if (leftNode == null && rightNode == null) {
                continue;
            }
//            if (leftNode == null && rightNode != null) {
//                return false;
//            }
//            if (leftNode != null && rightNode == null) {
//                return false;
//            }
//            if (leftNode.val != rightNode.val) {
//                return false;
//            }
            // 以上三个判断条件合并
            if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) {
                return false;
            }
            // 这里顺序与使用Deque不同
            deque.offer(leftNode.left);
            deque.offer(rightNode.right);
            deque.offer(leftNode.right);
            deque.offer(rightNode.left);
        }
        return true;
    }
100. 相同的树

跟上面那题做法一样

	
	public boolean isSameTree1(TreeNode p, TreeNode q) {
		if( p == null && q == null) return true;
		Queue queue = new linkedList<>();
		queue.offer(p);
		queue.offer(q);
		while(!queue.isEmpty()){

			TreeNode n1 = queue.poll();
			TreeNode n2 = queue.poll();
			if(n1 == null && n2 == null) continue;
			if(n1 == null || n2 == null || n1.val != n2.val) return false;
			//System.out.println("n1:" + n1.val + ", n2:" + n2.val);
			
			queue.offer(n1.left);
			queue.offer(n2.left);
			queue.offer(n1.right);
			queue.offer(n2.right);
		}		
		return true;
	}

	
	public boolean isSameTree(TreeNode p, TreeNode q) {
		return isSame(p, q);
	}
	public boolean isSame(TreeNode p, TreeNode q){
		if(p == null && q == null) return true;
		if(p == null || q == null || p.val != q.val) return false;
		
		boolean isl = isSame(p.left, q.left);
		boolean isr = isSame(p.right, q.right);
		
		return isl && isr;
	}
572. 另一棵树的子树

这题下线很低,上限很高

    遍历每一个结点,每一个结点判断是否相等kmp算法构造哈希,埃氏筛。不是给人做的
2. 平衡二叉树 110. 平衡二叉树

https://leetcode-cn.com/problems/balanced-binary-tree/

    递归(如果不平衡就是-1)迭代,没写
    public boolean isBalanced(TreeNode root) {
		return geth(root) != -1;
	}
	
	public int geth(TreeNode root) {
		if(root == null) return 0;
		int l = geth(root.left);
		if(l == -1) return -1;
		int r = geth(root.right);
		if(r == -1) return -1;
		if(Math.abs(l-r) > 1) return -1;		
		return Math.max(l, r) + 1;		
	}
3. 二叉树路径 257. 二叉树的所有路径

https://leetcode-cn.com/problems/binary-tree-paths/

		
	public List binaryTreePaths(TreeNode root) {
        List result = new ArrayList<>();
        if (root == null)
            return result;
        Stack stack = new Stack<>();
        // 节点和路径同时入栈
        stack.push(root);
        stack.push(root.val + "");
        while (!stack.isEmpty()) {
            // 节点和路径同时出栈
        	System.out.println(stack.toString());
            String path = (String) stack.pop();
            System.out.println(path);
            TreeNode node = (TreeNode) stack.pop();
            // 若找到叶子节点
            if (node.left == null && node.right == null) {
                result.add(path);
            }
            //右子节点不为空
            if (node.right != null) {
                stack.push(node.right);
                stack.push(path + "->" + node.right.val);
            }
            //左子节点不为空
            if (node.left != null) {
                stack.push(node.left);
                stack.push(path + "->" + node.left.val);
            }
        }
        return result;
    }
	
	
	
	public List binaryTreePaths1(TreeNode root) {
		List res = new ArrayList<>();
        if (root == null) return res;
        List paths = new ArrayList<>();
        traversal(root, paths, res);
        return res;
	}
		
	private void traversal(TreeNode root, List paths, List res) {
		paths.add(root.val);
		if(root.left == null && root.right == null){//碰到叶子结点
			StringBuilder sb = new StringBuilder();
			for(int i=0; i");
			}
			sb.append(paths.get(paths.size()-1));
			res.add(sb.toString());
			return;			
		}
		if(root.left != null){
			traversal(root.left, paths, res);
			paths.remove(paths.size()-1); //回溯
		}
		if(root.right != null){
			traversal(root.right, paths, res);
			paths.remove(paths.size()-1); //回溯
		}
	}
 
404. 左叶子之和 

https://leetcode-cn.com/problems/sum-of-left-leaves/

	
	public int sumOfLeftLeaves1(TreeNode root) {
		if(root == null) return 0;
		int suml = sumOfLeftLeaves1(root.left);
		int sumr = sumOfLeftLeaves1(root.right);
		
		int mid = 0;
		if( root.left != null && root.left.left == null && root.left.right == null){
			mid = root.left.val;
		}
			
		return mid + suml + sumr;
	}
	
	
	public int sumOfLeftLeaves(TreeNode root) {
		if(root == null) return 0;
		Stack stack = new Stack<> ();
		stack.add(root);
		int tosum = 0;
		while(!stack.isEmpty()){
			TreeNode node = stack.pop();
			if( node.left != null && node.left.left == null && node.left.right == null){
				tosum += node.left.val;
			}
			if( node.left != null) stack.add(node.left);
			if( node.right != null) stack.add(node.right);
		}
		return tosum;
	}
513. 找树左下角的值

https://leetcode-cn.com/problems/find-bottom-left-tree-value/

	
	public int findBottomLeftValue1(TreeNode root) {
		//1.如果root为空,返回0
		if(root == null) return 0;
		Queue queue = new linkedList<>();
		//2.把根节点放入队列
    	queue.offer(root);
    	List temp = new ArrayList(); 
		while(!queue.isEmpty()){
			temp.clear();
			int len = queue.size();
			while(len-->0){
				TreeNode n = queue.poll();
				temp.add(n.val);
				if(n.left != null) queue.add(n.left);
				if(n.right != null) queue.add(n.right);
			}
		}
		return temp.get(0);
	}
	
	
	
	int Deep = -1;
	int ans = 0;
	public int findBottomLeftValue(TreeNode root) {
		if( root == null ) return 0;
		findbigleft(root, 0);
		return ans;
	}
	
	public void findbigleft(TreeNode root, int deep){
		//if( deep > Deep ) ans = root.val; 
		if( root.left == null && root.right == null){
			if( deep > Deep ){
				ans = root.val; 
				Deep = deep;
			}
		}
		
		if(root.left != null) findbigleft(root.left, deep+1);
		if(root.right != null) findbigleft(root.right, deep+1);
	}
112. 路径总和
	
	public boolean hasPathSum1(TreeNode root, int targetSum) {
		if( root == null) return false;
		targetSum -= root.val;
		
		// 叶子结点
        if (root.left == null && root.right == null) {
            return targetSum == 0;
        }
			
		if(root.left != null){
			boolean l = hasPathSum(root.left, targetSum);
			if(l) return true;
		}
		if(root.right != null){
			boolean r = hasPathSum(root.right, targetSum);
			if(r) return true;
		}
		
		return false;
	}
	
	
	public boolean hasPathSum(TreeNode root, int targetSum) {
		//1. 空头直接否
		if( root == null) return false;
		//2. 碰到叶子节点判断
		if (root.left == null && root.right == null) return root.val == targetSum; 
		//3. 左右分支的并,有一条有就算有
		return hasPathSum(root.left, targetSum-root.val) || hasPathSum(root.right, targetSum-root.val);
	}
113. 路径总和 II

https://leetcode-cn.com/problems/path-sum-ii/
这题改了好几遍

	
	List> res = new ArrayList<>();
    List list = new ArrayList<>();	
	public List> pathSum(TreeNode root, int targetSum) {		
		dfs(root, 0, targetSum);				
		return res;
	}	
	public void dfs(TreeNode root, int num, int sum) {
		if( root == null ) return; 
		num += root.val;
		list.add(root.val);
		if( num == sum && root.left == null && root.right == null){
			res.add(new ArrayList(list));
		}
		dfs(root.left, num, sum);
		dfs(root.right, num, sum);
		list.remove(list.size()-1);//要回溯
	}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号