[Java算法]4、判断二叉树是否对称

算法题截图
上图是对称的二叉树示例

在这里插入图片描述
左节点的左指数,右节点的右指数
左节点的右指数,右节点的左指数
下面的代码用了两种做法

import java.util.Stack;

public class Fourth {
	public class TreeNode{
		int val;
		TreeNode left;
		TreeNode right;
		
		TreeNode(int x) { val = x; }
	}
	
	boolean isSymmetric(TreeNode s, TreeNode t) {
		if(s != null && t != null)
			return s.val == t.val &&
				isSymmetric(s.left, t.right) && isSymmetric(s.right, t.right);
		else return s == null && t == null;
	}
	
	//Time:O(n),Space: O(n)
	public boolean isSymmetricTreeRecursive(TreeNode root) {
		if (root == null) return true;
		return isSymmetric(root.left, root.right);
	}
	// Time: O(n),Space: O(n)
	public boolean isSymmetricTreeIterative(TreeNode root) {
		if(root == null) return true;
		Stack<TreeNode> stack = new Stack<>();
		stack.push(root.left);
		stack.push(root.right);
		
		while(!stack.empty()) {
			TreeNode s = stack.pop(), t = stack.pop();
			if(s == null && t == null) continue;
			if(s == null || t == null) return false;
			if(s.val != t.val) return false;
			
			stack.push(s.left);
			stack.push(t.right);
			stack.push(s.right);
			stack.push(t.left);
		}
		
		return false;
	}

}

猜你喜欢

转载自blog.csdn.net/qq_39400208/article/details/84454463
今日推荐