上圖是對稱的二叉樹示例
左節點的左指數,右節點的右指數
左節點的右指數,右節點的左指數
下面的代碼用了兩種做法
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;
}
public boolean isSymmetricTreeRecursive(TreeNode root) {
if (root == null) return true;
return isSymmetric(root.left, root.right);
}
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;
}
}