Symmetric Tree

来源:互联网 发布:注册会计师待遇 知乎 编辑:程序博客网 时间:2024/06/01 07:22

Symmetric Tree

题目描述:
对称树
思路:
递归和非递归两种方法实现,递归要有出口,非递归采用depth-first-search遍历。

1. 递归解法

此解法参考他人。

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool judge(TreeNode *lchild, TreeNode *rchild) {        if (lchild == 0 || rchild == 0) {            if (lchild == 0 && rchild == 0)                return true;            else                 return false;        }        if (lchild->val != rchild->val)            return false;        return judge(lchild->left, rchild->right) && judge(lchild->right, rchild->left);    }    bool isSymmetric(TreeNode* root) {        if (root == 0)            return true;        bool res;        res = judge(root->left, root->right);        return res;    }};

2. 非递归解法

非递归解法,稍后再补充。

0 0
原创粉丝点击