http://www.1point3acres.com/bbs/thread-127924-1-1.html
第二题有点像,给一个tree,返回每个点左右子树的和与自己值的差,用递归做,还问了不递归怎么做
第二题有点像,给一个tree,返回每个点左右子树的和与自己值的差,用递归做,还问了不递归怎么做
- public static ArrayList<Integer> treeNodeWithSubtreeSum(TreeNode root) {. 1point 3acres 璁哄潧
- ArrayList<Integer> ret = new ArrayList<Integer>();
- if (root == null). 1point 3acres 璁哄潧
- return ret;.鏈枃鍘熷垱鑷�1point3acres璁哄潧
- Stack<TreeNode> s = new Stack<TreeNode>();
- HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
- s.add(root);
- TreeNode pre = null;. 涓€浜�-涓夊垎-鍦帮紝鐙鍙戝竷
- while (!s.isEmpty()) {
- TreeNode cur = s.peek();
- if (pre == null || pre.left == cur || pre.right == cur) {
- if (cur.left != null) {
- s.push(cur.left);
- } else if (cur.right != null) {
- s.push(cur.right);
- } else {
- s.pop();
- map.put(cur.val, 0);. 鐗涗汉浜戦泦,涓€浜╀笁鍒嗗湴
- ret.add(cur.val - map.get(cur.val));
- }
- } else if (cur.left == pre) {
- if (cur.right != null) {
- map.put(cur.val, map.get(pre.val) + pre.val);
- s.push(cur.right);
- } else {.1point3acres缃�
- s.pop();
- map.put(cur.val, map.get(pre.val) + pre.val);
- ret.add(cur.val - map.get(cur.val));
- }
- } else if (cur.right == pre) {
- s.pop();
- int tmp = 0;
- if (map.containsKey(cur.val))
- tmp = map.get(cur.val);
- tmp += map.get(pre.val) + pre.val;
- map.put(cur.val, tmp);
- ret.add(cur.val - map.get(cur.val));
- }
- pre = cur;
- }. From 1point 3acres bbs
- return ret;
- }