[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;
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章