Java实现Leetcode题(二叉树-2)

发布时间:2024年01月03日

Leetcode226(翻转二叉树)

package tree;

import java.util.Deque;
import java.util.LinkedList;

public class LeetCode226 {
	public static void main(String[] args) {
		System.out.print("待定");
	}

	//递归
	public static void invertTree(TreeNode root) {
		if(root==null) {
			return;
		}
		swap(root);
		invertTree(root.left);
		invertTree(root.right);
	}
	public static void swap(TreeNode root) {
		TreeNode temp = root.right;
		root.right = root.left;
		root.left = temp;
	}
	//迭代
	public static void invertTree02(TreeNode root) {
		Deque<TreeNode> de = new LinkedList<>();
		if(root ==null) {
			return;
		}
		de.addFirst(root);
		while(!de.isEmpty()) {
			TreeNode temp = de.peekFirst();
			swap(temp);
			de.pollFirst();
			de.addFirst(temp.right);
			de.addFirst(temp.left);
		}
	}
}

Leetcode101(对称二叉树)

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left,root.right);
    }
    public static boolean compare(TreeNode left,TreeNode right) {
		if(left==null&&right!=null)return false;
		else if(right==null&&left!=null)return false;
		else if(right==null&&left==null)return true;
		else if(left.val!=right.val)return false;
		
		boolean outsize = compare(left.left,right.right);
		boolean insize = compare(left.right,right.left);
		return outsize&&insize;
	}
    //迭代法
     public boolean isSymmetric(TreeNode root) {
       if(root==null) {
			return true;
		}
		Deque<TreeNode> de = new LinkedList<>();
		de.addLast(root.left);
		de.addLast(root.right);
		while(!de.isEmpty()) {
			TreeNode left = de.peekFirst();
			de.pollFirst();
			TreeNode right = de.peekFirst();
			de.pollFirst();
			if(left==null&&right==null) {
				continue;
			}
			if(left==null||right==null||(left.val!=right.val)) {
				return false;
			}
			de.addLast(left.left);
			de.addLast(right.right);
			de.addLast(left.right);
			de.addLast(right.left);
		}
		return true;
    }
    
}

?

?

文章来源:https://blog.csdn.net/weixin_47059164/article/details/135374079
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。